Distinguish class property types through reflectio

2019-03-01 00:11发布

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?

How can I understand ID is struct or dimension is Interface? And Both String and Position are class but String is build in class, Position is Custom class.

3条回答
三岁会撩人
2楼-- · 2019-03-01 00:27

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

查看更多
仙女界的扛把子
3楼-- · 2019-03-01 00:44

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;
查看更多
该账号已被封号
4楼-- · 2019-03-01 00:49
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.

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.

if(prop.PropertyType.Assembly.GlobalAssemblyCache)
{
   // built-in type..
}
查看更多
登录 后发表回答