'casting' with reflection

前端 未结 6 1823
面向向阳花
面向向阳花 2020-11-30 21:47

Consider the following sample code:

class SampleClass
{
    public long SomeProperty { get; set; }
}

public void SetValue(SampleClass instance, decimal valu         


        
6条回答
  •  情歌与酒
    2020-11-30 22:29

    This is a very old question but I thought I'd chime in for ASP.NET Core Googlers.

    In ASP.NET Core, .IsNullableType() is protected (amongst other changes) so the code is a tad different. Here's @jeroenh's answer modified to work in ASP.NET Core:

    void SetValue(PropertyInfo info, object instance, object value)
    {
        Type proptype = info.PropertyType;
        if (proptype.IsGenericType && proptype.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
        {
            proptype = new NullableConverter(info.PropertyType).UnderlyingType;
        }
    
        var convertedValue = Convert.ChangeType(value, proptype);
        info.SetValue(instance, convertedValue);
    }
    

提交回复
热议问题