如何通过反射区分值类型、可为空值类型、枚举、可为空枚举、引用类型?
如何通过反射区分值类型、可为空值类型、枚举、可为空枚举、引用类型?
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 中的哪里可以检索这些信息?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
以下是检查 enum、nullable、primitve 和 value 类型的方法;
请注意,值类型和基元是不同的东西。基元只是映射到类型的简写(例如 bool > System.Boolean)。值类型按值传递;它们是结构而不是类。
Here is how you check for enum, nullable, primitve and value types;
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.
PropertyType.Name
似乎为非 Nullable 和 Nullable 类型提供了不同的输出。也许这对你有一点帮助。实际上,它给出了 Nullable`1 Int32 作为 Nullable 和 Non nullable 的输出。
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.