[英]Distinguish class property types through reflection
我有一個矩形課
public class Rectangle : Base, IRectangle
{
public IDimension dimension { get; set; }
public Position position { get; set; }
public String color { get; set; }
public int ID { get; set; }
public override String ToString()
{
return base.ToString(this);
}
}
是否可以通過Rectangle類定義的屬性的反射類型來區分?
我如何理解ID是struct或維度是Interface? 並且String和Position都是類,而String是在類中構建,Position是Custom類。
您可以使用以下屬性:
typeof(T).IsPrimitive
檢查類型是原始還是非原始
這個:
typeof(T).IsInterface
檢查類型是否為接口。
這是檢查類型是否為結構的方法:
typeof(T).IsValueType
如果您確實只在尋找“純”結構(而不只是一般的值類型),那么:
typeof(T).IsValueType && !typeof(T).IsEnum;
var prop = typeof(Rectangle).GetProperty("ID");
if(prop.PropertyType.IsValueType)
{
..
}
prop = typeof(Rectangle).GetProperty("dimension");
if(prop.PropertyType.IsInterface)
{
...
}
prop = typeof(Rectangle).GetProperty("color");
if(prop.PropertyType.IsClass)
{
...
}
您可能已經注意到, Type
類包含幾個屬性,您可以確定該類型是值類型,接口還是類等。
為了確定類類型是built-in
類型還是custom
類型,我認為您可以檢查是否從GAC(全局程序集緩存)中加載了該類型的Assembly
集。這不是最佳解決方案,但我不知道另一種方法。
if(prop.PropertyType.Assembly.GlobalAssemblyCache)
{
// built-in type..
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.