【发布时间】:2016-03-29 15:30:41
【问题描述】:
如果我有以下包装类:
public class Wrapper<T>
{
public T Data { get; set; }
public string[] Metadata { get;set;
}
然后另一个类在没有泛型的情况下公开该值:
public class SomeOtherClass
{
public object WrappedData { get;set };
}
,我怎样才能得到原始的解包数据?
我可以测试它,使用类似的东西:
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Wrapper<>))
{
dynamic originalValue = someOtherClass.WrappedData;
}
但我不能在originalValue 上调用.Data 属性,得到RuntimeBinderException。
更新
更多的上下文可能会有所帮助。我正在开发一个想要实现 HATEOAS 的 WebAPI。所以我的包装类包含将返回的数据和元数据,我正在编写一个动作过滤器,它将解包数据,在响应正文中返回它,并将元数据放入响应标头中。动作过滤器目前实现如下:
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
if (actionExecutedContext.Request.Method == HttpMethod.Get)
{
var objectContent = actionExecutedContext.Response.Content as ObjectContent;
if (objectContent != null)
{
var type = objectContent.ObjectType;
var formatter = actionExecutedContext
.ActionContext
.ControllerContext
.Configuration
.Formatters
.First(f => f.SupportedMediaTypes
.Contains(new MediaTypeHeaderValue(actionExecutedContext
.Response
.Content
.Headers
.ContentType
.MediaType)));
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Wrapper<>))
{
dynamic value = objectContent.Value;
actionExecutedContext.Response.Content = new ObjectContent(value.Data.GetType(), value.Data, formatter);
}
}
}
base.OnActionExecuted(actionExecutedContext);
}
显然,当前并非我所有的 API 端点都包装了它们的数据,所以如果响应没有返回 Wrapper<T> 实例,我想退出操作过滤器而不修改响应。如果是,则取出.Data的值,并用它重写响应体。
【问题讨论】:
-
WrapperData包含什么?如果它只包含Wrapper<T>.Data的值,那就很清楚了。如果它包含整个包装器,我们应该在初始化方面寻找问题。 -
什么包含
type变量?
标签: c# generics reflection