簡體   English   中英

根據其他對象的反射設置屬性類型

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

可以說我有兩節課:

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>();

我希望通過推斷設置該類型。 我知道如何通過獲取屬性從類中找到正確的屬性類型,我不確定如何設置容器類。

需要在編譯時知道屬性的類型。

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

無法在編譯時設置[the type of the objects key]

但是,您可以有一些選擇:

  1. 使用“對象”
  2. 創建多個類型並使用工廠來檢查密鑰的類型並使用它。
  3. 對所有ObjectViewModel對象使用字符串-字符串化int鍵

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM