Determine if reflected property can be assigned null

后端 未结 4 733
灰色年华
灰色年华 2020-12-15 16:15

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 f

相关标签:
4条回答
  • 2020-12-15 16:41
    PropertyInfo propertyInfo = ...
    bool canAssignNull = 
        !propertyInfo.PropertyType.IsValueType || 
        propertyInfo.PropertyType.IsGenericType &&
            propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>)
    
    0 讨论(0)
  • 2020-12-15 16:42

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

    if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
    

    Type would be your PropertyInfo.PropertyType

    0 讨论(0)
  • 2020-12-15 16:42

    Marc and Jonas both have parts to determine if a generic type can be assigned null.

    // A silly example. default(T) will return null if it is nullable. So no reason to check here. Except for the sake of having an example.
    public U AssignValueOrDefault<U>(object item)
    {
        if (item == null)
        {
            Type type = typeof(U); // Type from Generic Parameter
    
            // Basic Types like int, bool, struct, ... can't be null
            //   Except int?, bool?, Nullable<int>, ...
            bool notNullable = type.IsValueType ||
                               (type.IsGenericType && type.GetGenericTypeDefinition() != typeof(Nullable<>)));
    
            if (notNullable)
                return default(T);
        }
    
        return (U)item;
    }
    

    Note: Most of the time you can check if the variable is null. Then use default(T). It will return null by default of the object is a class.

    0 讨论(0)
  • 2020-12-15 16:45

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

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

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

    0 讨论(0)
提交回复
热议问题