简体   繁体   English

通过反射区分类属性类型

[英]Distinguish class property types through reflection

I have a Rectangle class 我有一个矩形课

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

Are there any way to distinguish through reflection types of properties which defined on Rectangle class? 是否可以通过Rectangle类定义的属性的反射类型来区分?

How can I understand ID is struct or dimension is Interface? 我如何理解ID是struct或维度是Interface? And Both String and Position are class but String is build in class, Position is Custom class. 并且String和Position都是类,而String是在类中构建,Position是Custom类。

You can use this property: 您可以使用以下属性:

typeof(T).IsPrimitive

To check if a type is primitive or non-primitive 检查类型是原始还是非原始

This one: 这个:

typeof(T).IsInterface

To check if a type is an interface or not. 检查类型是否为接口。

This is how you check is a type is a struct or not: 这是检查类型是否为结构的方法:

typeof(T).IsValueType

In case you are truly looking only for "pure" structs (not just value types in general) then: 如果您确实只在寻找“纯”结构(而不​​只是一般的值类型),那么:

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)
{
   ...
}

As you might have noticed Type class contains several properties that you can determine whether the type is a value type,or interface or class etc. 您可能已经注意到, Type类包含几个属性,您可以确定该类型是值类型,接口还是类等。

To determine whether the class type is built-in type or custom type, I think you can check whether type's Assembly is loaded from the GAC (Global assembly cache) or not.It's not the best solution but I don't know another way. 为了确定类类型是built-in类型还是custom类型,我认为您可以检查是否从GAC(全局程序集缓存)中加载了该类型的Assembly 集。这不是最佳解决方案,但我不知道另一种方法。

if(prop.PropertyType.Assembly.GlobalAssemblyCache)
{
   // built-in type..
}

the above answer are good. 以上答案都很好。 BUT if you something that is extensible, you can create your own custom Custom Attributes and use reflection on that Type. 但是,如果您可以扩展某些内容,则可以创建自己的自定义定义属性,并在该类型上使用反射。

For example, you can create attribute that's contain how to print properties or how to validate them, get those all with reflection. 例如,您可以创建包含如何打印属性或如何验证属性的属性,并通过反射获得所有属性。

we use this way to create protocol parser, where each properties we define the order in the protocol, the length, and the validation - But again - this can be over killer for you 我们使用这种方式来创建协议解析器,其中每个属性我们都定义了协议的顺序,长度和验证-但同样,这可能对您来说是致命的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM