【发布时间】:2018-07-25 23:59:52
【问题描述】:
假设我有两个类:
public class IntKeyObject{
public int Id {get;set;}
[ForeignKey]
public int ForeignKey {get;set;}
public string SomeProperty {get;set;}
...
}
public class StringKeyObject{
public string Id {get;set;}
[ForeignKey]
public string ForeignKey {get;set;}
public string SomeOtherProperty {get;set;}
}
我希望能够像这样创建一个容器类:
public class ObjectViewModel<T>{
public [the type of the objects key] ForeignKey {get;set;}
public IEnumerable<T> MyList {get;set;}
}
我在哪里初始化它,如下所示:
new ObjectViewModel<IntKeyObject>();
有没有办法在对象类型上使用反射来设置我的 ForeignKey 属性类型? 现在我知道如何做到这一点的唯一方法是显式传递 Key 类型,如下所示:
new ObjectViewModel<IntKeyObject, int>();
new ObjectViewModel<StringKeyObject, string>();
我更愿意通过推理来设置该类型。我知道如何通过获取属性从类中找到正确的属性类型,但我不确定如何设置我的容器类。
【问题讨论】:
-
泛型必须在编译时已知,反射在运行时运行。所以,简短的回答,不,你不能推断你不知道什么
-
假设您使用反射创建了这个对象,那么您希望如何使用它?
标签: c# reflection custom-attributes