确定反射属性可以分配空反射、属性、分配

2023-09-03 02:23:01 作者:往事隔山水

我要自动的发现对所提供的类中的一些信息,以做一些类似于形成条目。特别是我使用反射来换取每个属性的PropertyInfo值。我可以读取或写入值从我的形式的每个属性,但如果该属性被定义为INT,我就不能和我的程序不应该去尝试,写一个空值。

I wish to automagically discover some information on a provided class to do something akin to form entry. Specifically I am using reflection to return a PropertyInfo value for each property. I can read or write values to each property from my "form", but if the property is defined as "int", I would not be able to, and my program should not even try, to write a null value.

我如何使用反射来确定给定的属性可以被赋予一个空值,而不需要编写一个switch语句来检查每一个可能的类型?我特别想检测盒装类型如诠释与诠释?之间的区别,因为在第二种情况下我的执行的希望能够写一个空值。该IsValueType和IsByRef似乎还没有看到一个区别。

How can I use reflection to determine if a given property can be assigned a null value, without writing a switch statement to check for every possible type? In particular I want to detect the difference between boxed types like "int" vs. "int?", since in the second case I do want to be able to write a null value. The IsValueType and IsByRef don't seem to see a difference.

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;}
}

请注意,我需要长时间来确定这些信息之前,我确实尝试写的值,所以使用异常处理缠的SetValue是不是一种选择。

Note that I need to determine this information long before I actually attempt to write the value, so using exception handling wrapped around SetValue is not an option.

推荐答案

您需要处理引用和可空< T> ,因此(反过来):

You need to handle null references and Nullable<T>, so (in turn):

bool canBeNull = !type.IsValueType || (Nullable.GetUnderlyingType(type) != null);

注意 IsByRef 是不同的东西,可以让你的 INT 选择和 REF INT / OUT INT

Note that IsByRef is something different, that allows you to choose between int and ref int / out int.