How to differentiate between value-type, nullable value-type, enum, nullable-enum, reference-types through reflection?

假装没事ソ 提交于 2019-12-21 17:56:34

问题


How to differentiate between value-type, nullable value-type, enum, nullable-enum, reference-types through reflection?

enum MyEnum
    {
        One,
        Two,
        Three
    }

    class MyClass
    {
        public int IntegerProp { get; set; }
        public int? NullableIntegerProp { get; set; }
        public MyEnum EnumProp { get; set; }
        public MyEnum? NullableEnumProp { get; set; }
        public MyClass ReferenceProp { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {   
            Type classType = typeof(MyClass);

            PropertyInfo propInfoOne = classType.GetProperty("IntegerProp");
            PropertyInfo propInfoTwo = classType.GetProperty("NullableIntegerProp");
            PropertyInfo propInfoThree = classType.GetProperty("EnumProp");
            PropertyInfo propInfoFour = classType.GetProperty("NullableEnumProp");
            PropertyInfo propInfoFive = classType.GetProperty("ReferenceProp");

            propInfoOne.???
            ...............
            ...............
        }
    }

Where in the propInfo...s these information can be retrieved?


回答1:


Here is how you check for enum, nullable, primitve and value types;

Console.WriteLine(propInfoOne.PropertyType.IsPrimitive); //true
Console.WriteLine(propInfoOne.PropertyType.IsValueType); //false, value types are structs

Console.WriteLine(propInfoThree.PropertyType.IsEnum); //true

var nullableType = typeof (Nullable<>).MakeGenericType(propInfoThree.PropertyType);
Console.WriteLine(nullableType.IsAssignableFrom(propInfoThree.PropertyType)); //true

Note that value types and primitives are different things. Primitives are simply shorthands that map to types (e.g bool > System.Boolean). Value types are passed by value; they are struct(ure)s not classes.




回答2:


    public void Test(Type desiredType, object value)
    {
        if (desiredType.IsGenericType)
        {
            if (desiredType.GetGenericTypeDefinition() == typeof(Nullable<>))
            {
                if (value == null)
                {
                }
            }
        }
    }



回答3:


The PropertyType.Name seems to be giving different output for Non Nullable and Nullable types. May be this could be a bit of help to you.

Actually it gives Nullable`1 Int32 as the output for Nullable and Non nullable.



来源:https://stackoverflow.com/questions/8614624/how-to-differentiate-between-value-type-nullable-value-type-enum-nullable-enu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!