PropertyInfo SetValue and nulls

前端 未结 2 566
Happy的楠姐
Happy的楠姐 2021-02-14 09:35

If I have something like:

object value = null;
Foo foo = new Foo();

PropertyInfo property = Foo.GetProperties().Single(p => p.Name == \"IntProperty\");
prope         


        
2条回答
  •  星月不相逢
    2021-02-14 09:57

    If you have the PropertyInfo, you can check the .PropertyType; if .IsValueType is true, and if Nullable.GetUnderlyingType(property.PropertyType) is null, then it is a non-nullable value-type:

            if (value == null && property.PropertyType.IsValueType &&
                Nullable.GetUnderlyingType(property.PropertyType) == null)
            {
                throw new InvalidCastException ();
            }
    

提交回复
热议问题