Cast a property to its actual type dynamically using reflection

后端 未结 7 976
梦毁少年i
梦毁少年i 2020-12-09 08:29

I need to cast a property to its actual type dynamically. How do I/Can I do this using reflection?

To explain the real scenario that I am working on a bit. I am tryi

相关标签:
7条回答
  • 2020-12-09 09:04
    Type resultType = typeof(T);
    IEnumerable<PropertyDescriptor> properties = TypeDescriptor.GetProperties(resultType).Cast<PropertyDescriptor>();
    
    object instance = Activator.CreateInstance(resultType);
    
    var objValue = "VALUE FOR HEADER";
    var resultHeader = "HeaderName";
    var prop = properties.Single(p => string.Equals(p.Name, resultHeader, StringComparison.InvariantCultureIgnoreCase));
    
    var targetType = Nullable.GetUnderlyingType(prop.PropertyType) !=null Nullable.GetUnderlyingType(prop.PropertyType):prop.PropertyType;
    
    objValue  = Convert.ChangeType(objValue , targetType);
    prop.SetValue(instance, objValue );
    

    //return instance;

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