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

use*_*312 4 c# reflection propertyinfo

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

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.???
            ...............
            ...............
        }
    }
Run Code Online (Sandbox Code Playgroud)

在propInfo中,哪些信息可以被检索?

Myl*_*ell 6

以下是检查enum,nullable,primitve和value类型的方法;

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
Run Code Online (Sandbox Code Playgroud)

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

  • 我看到你相信值类型存储在堆栈中的谎言.值类型存储在堆栈中,除非它们没有存储在堆栈中,这几乎总是如此. (7认同)
  • @ProgrammingHero并不完全正确; 原语通常指具有**直接**IL支持的原语; 例如,`int`,`short`,`byte`,`long`,`float`等都有**直接**IL支持; 诸如`+`之类的操作不使用类型运算符,而是IL指令.例如,对比"十进制",它不是**原始的.他们非常**被**区别对待.实际上,在堆栈中大多数甚至都不存在:`byte`,`sbyte`,`short`,`ushort`等都在IL级别使用`int`(在操作期间;不作为它们的声明). (2认同)
  • @Myles - 检查`Nullable <T>`的更好方法是使用`Nullable.GetUnderlyingType` (2认同)