如何通过反射区分值类型、可空值类型、枚举、可空枚举、引用类型?
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…这些信息可以检索吗?
如何检查枚举、可空类型、基本类型和值类型;
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)。值类型按值传递;它们是结构体而不是类
public void Test(Type desiredType, object value)
{
if (desiredType.IsGenericType)
{
if (desiredType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
if (value == null)
{
}
}
}
}
PropertyType.Name
似乎为非空和可空类型提供了不同的输出。也许这能帮到你。
实际上它给出Nullable ' 1 Int32作为Nullable和Non Nullable的输出