如果属性类C#使用反射,如何获取属性值?

时间:2014-12-19 16:46:27

标签: c# .net reflection

我有两个班级

public class A
{
   public string Name {get; set;}
}

public class B
{
   public A A {get; set;}
}

如何从A的对象B属性中获取Name的值?

现在我用

        string fromName = GetPropertyName(from);
        string toName = GetPropertyName(to);

        PropertyInfo oldProperty = typeof(T).GetProperty(toName);
        PropertyInfo newProperty = typeof(T).GetProperty(fromName);

        var oldValue = newProperty.GetValue(item);

        if (cryptVal != null && !string.IsNullOrWhiteSpace(oldValue.ToString()))
        {
            string newVal = provider.get(oldValue.ToString());

            property.SetValue(item, newVal, null);
        }

        private static string GetPropertyName<T>(Expression<Func<T,object>> property)
        {
            var memberNames = new List<string>();

            var memberExpression = property.Body as MemberExpression;

            while (null != memberExpression)
            {
                memberNames.Add(memberExpression.Member.Name);
                memberExpression = memberExpression.Expression as MemberExpression;
            }

            memberNames.Reverse();

            return string.Join(".", memberNames.ToArray());
        }

但是按名称获取值Device.Name不可能:)。在这里我认为需要检查属性名称是否有点,需要使用Split并获取值对象类然后获取属性。但也许还有其他变种?

1 个答案:

答案 0 :(得分:0)

 var b = new B();

 b.A = new A()
 {
    Name = "Hello World"
 };

 Console.WriteLine(b.A.Name);