Setting properties of an object through reflection with different properties types

前端 未结 1 569
孤城傲影
孤城傲影 2020-12-19 09:47

I am using reflection to populate the properties of an object.

These properties have different types: String, Nullable(double) and Nullable(long) (don\'t know how t

相关标签:
1条回答
  • 2020-12-19 10:33

    If the values are already of the correct type, then no: you don't have to do anything. If they might not be right (int vs float, etc), the a simple approach might be:

    (edit adjusted for nulls)

    Type propertyType = info.PropertyType;
    if (thisPropertyValue != null)
    {
        Type underlyingType = Nullable.GetUnderlyingType(propertyType);
        thisPropertyValue = Convert.ChangeType(
            thisPropertyValue, underlyingType ?? propertyType);
    }
    info.SetValue(this, thisPropertyValue, null);
    
    0 讨论(0)
提交回复
热议问题