簡體   English   中英

如何使用反射確定已實現接口的通用類型?

[英]How do I determine the generic type of an implemented interface using reflection?

我寫的東西需要使用反射在運行時發現對象中所有屬性的類型。 我對簡單的屬性沒問題,我只獲取了PropertyInfo並且該類型可以直接使用。 但是,我不知道該如何處理通用集合。 例如,假設我在運行時獲得了以下類的實例:

public class AnyClass
  {
  public ICollection<int> ListOfInts;
  }

因此,我使用Type.GetProperties並且很快我有了ListOfInts PropertyInfo對象。

我下一步是什么? 我如何從擁有PropertyInfo到確定它是一個整數列表? 如何僅從PropertyInfo確定集合的通用類型(在本例中為<int> )?

您可以獲取通用參數類型的名稱:

propertyInfo.PropertyType.GetGenericArguments()[0].Name

我相信您正在尋找該類型的通用參數。 請參見PropertyInfo.PropertyTypeType.GenericTypeArguments

PropertyInfo.PropertyType.GenericTypeArgument

暫無
暫無

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

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