C# 通过反射设置对象属性的对象属性
我使用SO问题来使用反射检索对象的属性。我检索到的属性是另一个对象,它有一个名为C# 通过反射设置对象属性的对象属性,c#,generics,reflection,C#,Generics,Reflection,我使用SO问题来使用反射检索对象的属性。我检索到的属性是另一个对象,它有一个名为Value的属性,我需要访问该属性。我使用反射检索的所有潜在对象都来自同一个类EntityField,因此都具有Value属性。我看到了很多问题,这些问题暗示了我如何能够访问Value属性,但我不能很好地组合正确的代码。如何访问反射检索的对象的值属性 我的尝试 实体字段 公共类EntityField:EntityFieldBase { 私有字段_字段; 私人T_值; 公共实体字段(字段,T值){ 这个。_字段=字段;
Value
的属性,我需要访问该属性。我使用反射检索的所有潜在对象都来自同一个类EntityField
,因此都具有Value
属性。我看到了很多问题,这些问题暗示了我如何能够访问Value
属性,但我不能很好地组合正确的代码。如何访问反射检索的对象的值
属性
我的尝试
实体字段
公共类EntityField:EntityFieldBase
{
私有字段_字段;
私人T_值;
公共实体字段(字段,T值){
这个。_字段=字段;
此值为._值=值;
}
公共领域
{
得到
{
返回此.\u字段;
}
设置
{
如果(此._字段!=值)
{
此._字段=值;
}
}
}
公共价值
{
得到
{
返回此值;
}
设置
{
如果(!EqualityComparer.Default.Equals)(此值,值))
{
此值为._值=值;
这是真的;
}
}
}
}
试试这个:
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);
}
类TestChild
{
公共childt属性{get;set;}
}
类TestParent
{
公共TestChild ParentProperty{get;set;}
}
void Main()
{
var实例=新的TestParent
{
ParentProperty=newtestchild()
};
instance.GetType()
.GetProperty(“父属性”)
.GetValue(实例)
.GetType()
.GetProperty(“儿童财产”)
.SetValue(instance.ParentProperty,“Value”);
WriteLine(instance.ParentProperty.ChildProperty);
}
有一个名为属性的属性
,但该属性是一个对象,而不是系统类型(例如字符串、int)。我需要从对象访问一个属性,该属性是传递给SetValue的对象上的属性。我明白了。在这种情况下,您只需检索该对象并在该对象上运行相同的代码:)这与您只需在属性返回的对象上运行它的代码相同。我认为这非常接近……不幸的是,Test
实际上是一个泛型Test
,因此我需要以某种方式将动态类型传递给泛型对象啊,抱歉-没有注意到问题的一般方面。已经修改了答案。我正在研究在运行时不知道类型时如何执行此操作。例如,测试可能有T=String、T=int、T=Guid等。有什么想法吗?只需再次修改答案以说明…:)感谢您的帮助:)如果您有一个子属性为TestField
的Test
,您会怎么做?我可以在Test
上访问TestField
,但我需要访问Test.TestField.Value
entity.GetType().GetProperty("Value").SetValue(entity, obj["Value"], null);
entity.Property.GetType().GetProperty("Value").SetValue(entity, obj["Value"], null);
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);
}