4

如何通过反射区分值类型、可空值类型、枚举、可空枚举、引用类型?

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.???
            ...............
            ...............
        }
    }

在 propInfo...s 的什么地方可以检索到这些信息?

4

3 回答 3

6

以下是检查枚举、可为空、原始和值类型的方法;

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

请注意,值类型和原语是不同的东西。基元只是映射到类型的简写(例如 bool > System.Boolean)。值类型是按值传递的;它们是结构(ure)而不是类。

于 2011-12-23T10:04:10.280 回答
2
    public void Test(Type desiredType, object value)
    {
        if (desiredType.IsGenericType)
        {
            if (desiredType.GetGenericTypeDefinition() == typeof(Nullable<>))
            {
                if (value == null)
                {
                }
            }
        }
    }
于 2011-12-23T10:37:16.193 回答
0

PropertyType.Name似乎为 Non Nullable 和 Nullable 类型提供了不同的输出。可能这对你有点帮助。

实际上它给出了Nullable`1 Int32作为 Nullable 和 Non nullable 的输出。

于 2011-12-23T10:28:11.353 回答