通过它在asp.net路径获取属性值 [英] get value of a property by its path in asp.net

查看:81
本文介绍了通过它在asp.net路径获取属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里一个解决方案是考虑到获取属性值通过提供其名称的类。现在我不知道我该怎么做同样在这种情况下:

here a solution is given to get value of a property of a class by supplying its name . now I wonder how I can do the same in this condition :

我有一个类的 MyClass的。这类公顷类型的属性的名为。在有类型的属性的名为即可。和酒吧有一个名为的字符串属性的

I have a class MyClass . this class ha a property of type Foo named foo . the Foo has a property of type Bar named bar . and bar has a string property named value .

属性不是一成不变的。

我希望能够拿到价值的 foo.bar.value 通过将字符串foo.bar.value为propertyName的。在其他的话,我想通过属性路径来获得它的值。

I want to be able to get value of foo.bar.value by passing the string "foo.bar.value" as propertyName . in other word I want to pass the property path to get its value .

这可能吗?

推荐答案

您可以用递归方法做到这一点。每次通话取值与第一个字的路径,并与剩下的部分再次调用该方法。

You can do this with a recursive method. Each call takes the value with the first word in path and call the method again with the rest of the part.

public object GetPropertyValue(object o, string path)
{
    var propertyNames = path.Split('.');
    var value = o.GetType().GetProperty(propertyNames[0]).GetValue(o, null);

    if (propertyNames.Length == 1 || value == null)
        return value;
    else
    {
        return GetPropertyValue(value, path.Replace(propertyNames[0] + ".", ""));
    }
}

这篇关于通过它在asp.net路径获取属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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