[英]Set Object Property of Object Property by Reflection
我用这个 SO问题来使用反射来检索对象的属性。 我检索的属性是另一个对象,该对象具有我需要访问的名为Value
的属性。 我使用反射检索的所有潜在对象均来自同一类EntityField
,因此都具有Value
属性。 我看到了这样的问题,它暗示了我如何能够访问Value
属性,但是我不能完全将正确的代码组合在一起。 如何访问通过反射检索的对象的Value
属性?
var parent = entity.GetType().GetProperty("Property");
parent.GetType().GetProperty("Value").SetValue(parent, newValue); // parent.GetType() is null
(parent as EntityField<T>).Value = newValue; // Not sure how to dynamically set T since it could be any system type
private static void SetValues(JObject obj, EntityBase entity)
{
// entity.GetType().GetProperty("Property") returns an EntityField Object
// I need to set EntityField.Value = obj["Value"]
// Current code sets EntityField = obj["Value"] which throws an error
entity.GetType().GetProperty("Property").SetValue(entity, obj["Value"], null);
}
public class EntityField<T> : EntityFieldBase
{
private Field _Field;
private T _Value;
public EntityField(Field field, T value){
this._Field = field;
this._Value = value;
}
public Field Field
{
get
{
return this._Field;
}
set
{
if (this._Field != value)
{
this._Field = value;
}
}
}
public T Value
{
get
{
return this._Value;
}
set
{
if (!EqualityComparer<T>.Default.Equals(this._Value, value))
{
this._Value = value;
this._IsDirty = true;
}
}
}
}
尝试这个:
entity.GetType().GetProperty("Value").SetValue(entity, obj["Value"], null);
您需要在GetProperty()方法中指定属性的名称。 我怀疑没有所谓的“属性” :)
编辑:阅读您的评论后,尝试
entity.Property.GetType().GetProperty("Value").SetValue(entity, obj["Value"], null);
在LinqPad中尝试了以下方法,它确实有效...
class TestChild<T>
{
public T ChildProperty { get; set; }
}
class TestParent<T>
{
public TestChild<T> ParentProperty { get; set; }
}
void Main()
{
var instance = new TestParent<string>
{
ParentProperty = new TestChild<string>()
};
instance.GetType()
.GetProperty("ParentProperty")
.GetValue(instance)
.GetType()
.GetProperty("ChildProperty")
.SetValue(instance.ParentProperty, "Value");
Console.WriteLine(instance.ParentProperty.ChildProperty);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.