确定是否可以将反射属性指定为null

Dav*_*vid 35 .net c# reflection

我希望自动发现有关提供的类的一些信息,以执行类似于表单输入的操作.具体来说,我使用反射为每个属性返回PropertyInfo值.我可以从我的"表单"中读取或写入每个属性的值,但如果属性被定义为"int",我将无法编写空值,我的程序甚至不能尝试.

如何使用反射来确定是否可以为给定属性分配空值,而无需编写switch语句来检查每种可能的类型?特别是我想检测像"int"和"int?"这样的盒装类型之间的区别,因为在第二种情况下我确实希望能够写出一个空值.IsValueType和IsByRef似乎没有区别.

public class MyClass
{
    // Should tell me I cannot assign a null
    public int Age {get; set;} 
    public DateTime BirthDate {get; set;}
    public MyStateEnum State {get; set;}
    public MyCCStruct CreditCard {get; set;}

    // Should tell me I can assign a null
    public DateTime? DateOfDeath {get; set;}
    public MyFamilyClass Famly {get; set;}
}
Run Code Online (Sandbox Code Playgroud)

请注意,我需要在实际尝试写入值之前很久才确定此信息,因此使用围绕SetValue的异常处理不是一种选择.

Mar*_*ell 79

你需要处理null引用Nullable<T>,所以(反过来):

bool canBeNull = !type.IsValueType || (Nullable.GetUnderlyingType(type) != null);
Run Code Online (Sandbox Code Playgroud)

请注意,这IsByRef是不同的,允许您在/ int和之间进行选择.ref intout int

  • 数组是引用类型,因此它们与类的工作方式相同. (2认同)
  • @pqsk因为问题是“...可以分配为空”;需要考虑引用类型 (2认同)

Jon*_*oln 9

来自http://msdn.microsoft.com/en-us/library/ms366789.aspx

if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
Run Code Online (Sandbox Code Playgroud)

Type 会是你的 PropertyInfo.PropertyType


小智 5

PropertyInfo propertyInfo = ...
bool canAssignNull = 
    !propertyInfo.PropertyType.IsValueType || 
    propertyInfo.PropertyType.IsGenericType &&
        propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>)
Run Code Online (Sandbox Code Playgroud)