【问题标题】:Set property type based on reflection of another object根据另一个对象的反射设置属性类型
【发布时间】: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


【解决方案1】:

需要在编译时知道属性的类型。

 public [the type of the objects key] ForeignKey {get;set;}

不能在编译时设置[the type of the objects key]

但是,您可以有一些选择:

  1. 使用“对象”
  2. 创建多种类型并使用工厂检查密钥的类型并使用它。
  3. 对所有 ObjectViewModel 对象使用字符串 - 字符串化 int 键

【讨论】:

  • 谢谢,不确定是否可行,但必须确定!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-21
  • 2010-10-26
  • 1970-01-01
  • 1970-01-01
  • 2010-10-11
相关资源
最近更新 更多