通过reflection区分类属性类型

我有一个Rectangle类

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类中定义的reflection类型的属性?

我怎样才能理解ID是结构还是维度是接口? 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.. } 

以上答案都很好。 但是如果你是可扩展的东西,你可以创建自己的自定义自定义属性并在该类型上使用reflection。

例如,您可以创建包含如何打印属性或如何validation属性的属性,通过reflection获取所有属性。

我们使用这种方式来创建协议解析器,其中每个属性我们定义协议中的顺序,长度和validation – 但同样 – 这对你来说可能是过度杀手