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

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

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

最佳答案

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

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)而不是类。

关于c# - 如何通过反射区分值类型、可空值类型、枚举、可空枚举、引用类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8614624/

相关文章:

c# - 无需在 CRM 2011 中调用 AssignRequest 即可创建具有特定所有者的新记录

c# - 为什么即使没有其类的实例,成员常量也可用?

Java反射: Creating class instance dynamically and assigning it to Parent object

java - 类对象无法解析为类型

c# - 反射 PropertyInfo SetValue C#

c# - 错误 : 0x1 at XX: Exception has been thrown by the target of an invocation

c# - 将方法转换为 C# 源代码

c# - 将属性传递给 C# 中的方法

c# - 如何通过反射获取类中某个属性的 "class type"?

c# - 从字符串中获取特定位置的最佳方法