使用反射来设置的对象的属性的属性 [英] Using reflection to set a property of a property of an object

查看:114
本文介绍了使用反射来设置的对象的属性的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个班。

public class Class1 {
   public string value {get;set;}
}

public class Class2 {
   public Class1 myClass1Object {get;set;}
}

我有型的Class2的对象。我需要使用反思Class2中设置值属性...即,如果我不这样做反思它,这是我怎么会去一下:

I've got an object of type Class2. I need to use reflection on Class2 to set the value property... i.e, if I were doing it without reflection, this is how I would go about it:

Class2 myObject = new Class2();
myObject.myClass1Object.value = "some value";

有没有办法做到以上,而使用反射来访问属性myClass1Object.value?

Is there a way to do the above, while using reflection to access the property "myClass1Object.value" ?

先谢谢了。

推荐答案

基本上它分成两个属性访问。首先,你的 GET 的的 myClass1Object 属性,那么你的设置的的的result属性。

Basically split it into two property accesses. First you get the myClass1Object property, then you set the value property on the result.

显然,你需要采取的任何格式,你已经得到的属性名和分裂出来 - 例如用点。例如,这应该做性能的任意深度:

Obviously you'll need to take whatever format you've got the property name in and split it out - e.g. by dots. For example, this should do an arbitrary depth of properties:

public void SetProperty(object source, string property, object target)
{
    string[] bits = property.Split('.');
    for (int i=0; i < bits.Length - 1; i++)
    {
         PropertyInfo prop = source.GetType().GetProperty(bits[i]);
         source = prop.GetValue(source, null);
    }
    PropertyInfo propertyToSet = source.GetType()
                                       .GetProperty(bits[bits.Length-1]);
    propertyToSet.SetValue(source, target, null);
}

诚然,你可能要多一点错误检查比:)

Admittedly you'll probably want a bit more error checking than that :)

这篇关于使用反射来设置的对象的属性的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆