通过asp.net中的路径获取属性的值

时间:2012-08-27 11:31:56

标签: c# asp.net reflection

here给出了一个解决方案,通过提供其名称来获取类的属性值。现在我想知道在这种情况下我怎么能做同样的事情:

我有一个课程 MyClass 。此类具有 Foo 类型的属性,名为 foo Foo 具有 Bar 类型的属性,名为 bar 。和bar有一个名为 value 的字符串属性。

属性不是静态的。

我希望通过将字符串“foo.bar.value”作为propertyName传递来获取 foo.bar.value 的值。换句话说,我想传递属性路径来获取它的值。

有可能吗?

4 个答案:

答案 0 :(得分:5)

您可以使用递归方法执行此操作。每个调用都使用路径中第一个单词的值,并使用部分的其余部分再次调用该方法。

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] + ".", ""));
    }
}

答案 1 :(得分:4)

这假定属性的命名类似于类。即类型Foo的属性也被命名为Foo。没有这个假设,问题就是缺少一些关键信息。

您可以使用string.Split method将字符串foo.bar.value分隔开来。然后,您将拥有一个数组,每个属性名称包含一个元素。

迭代该数组并使用PropertyInfo.GetValue检索属性的值。在一个操作中返回的值是在下一次迭代中传递给GetValue的实例。

string props = "foo.bar.value";
object currentObject = // your MyClass instance

string[] propertyChain = props.Split('.');
foreach (string propertyName in propertyChain) {
    if (propertyName == "") {
        break;
    }

    PropertyInfo prop = currentObject.GetType().GetProperty(propertyName);
    currentObject = prop.GetValue(currentObject);
    if (currentObject == null) {
        // somehow handle the situation that one of the properties is null
    }
}

更新:我添加了一项安全措施,以确保即使props为空也能正常工作。在这种情况下,currentObject仍将是对原始MyClass实例的引用。

答案 2 :(得分:1)

当你在这里指出问题的答案时,你需要利用Reglection来实现同样的目的。

借助反思你可以阅读财产的价值。

这样的事,

// dynamically load assembly from file Test.dll
Assembly testAssembly = Assembly.LoadFile(@"c:\Test.dll");
// get type of class Calculator from just loaded assembly
Type calcType = testAssembly.GetType("Test.Calculator");
// create instance of class Calculator
object calcInstance = Activator.CreateInstance(calcType);
// get info about property: public double Number
PropertyInfo numberPropertyInfo = calcType.GetProperty("Number");
// get value of property: public double Number
double value = (double)numberPropertyInfo.GetValue(calcInstance, null);

您需要将代码放在一个函数中,而不是根据您的要求拆分字符串

public object getvalue(string propname)
{
  //above code with return type object 
}
String[] array = string.Split("foo.bar.value");
//call above method to get value of property..

阅读详情:http://www.csharp-examples.net/reflection-examples/

答案 3 :(得分:1)

假设FOO是静态的,你可以从这样的字符串中获取类:

C# Reflection: How to get class reference from string?

...然后使用您链接到的其他帖子从中获取属性和值:

Get property Value by its stringy name

如果FOO不是静态的,则需要在实例上使用反射(这将否定将类的名称作为字符串传递的要求,因为您可以使用GetType从实例获取类( )) - 记住Bar在类中没有值,除非它是静态的。