简体   繁体   English

根据其他对象的反射设置属性类型

[英]Set property type based on reflection of another object

Lets say I have two classes: 可以说我有两节课:

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;}
}

I would like to be able to make an container class as such: 我希望能够使这样的容器类:

public class ObjectViewModel<T>{
     public [the type of the objects key] ForeignKey {get;set;}
     public IEnumerable<T> MyList {get;set;}
}

where I initialize it like below: 我将其初始化如下:

new ObjectViewModel<IntKeyObject>();

Is there a way to use reflection on the object type to set my ForeignKey property type? 有没有一种方法可以使用对对象类型的反射来设置我的ForeignKey属性类型? Right now the only way I know how to do it is by explicitly passing in the Key type like so: 现在,我知道如何做的唯一方法是通过显式传递Key类型,如下所示:

new ObjectViewModel<IntKeyObject, int>();
new ObjectViewModel<StringKeyObject, string>();

I would prefer to set that type by inference. 我希望通过推断设置该类型。 I know how to find the correct property type from a class by getting the attribute, what I'm not sure about is how to set up my container class. 我知道如何通过获取属性从类中找到正确的属性类型,我不确定如何设置容器类。

The type of the property needs to be knows at compile time. 需要在编译时知道属性的类型。

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

Setting [the type of the objects key] not at compile time is not possible. 无法在编译时设置[the type of the objects key]

However, you can have some options: 但是,您可以有一些选择:

  1. use 'object' 使用“对象”
  2. Create multiple types and use a factory that will check what the type of the key is and use that. 创建多个类型并使用工厂来检查密钥的类型并使用它。
  3. Use string for all ObjectViewModel objects - stringify the int key 对所有ObjectViewModel对象使用字符串-字符串化int键

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM