[英]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.