2

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 :

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 .

properties are not static .

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 .

is it possible ?

4

4 回答 4

5

您可以使用递归方法来做到这一点。每个调用都使用 path 中的第一个单词获取值,并使用该部分的其余部分再次调用该方法。

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] + ".", ""));
    }
}
于 2012-08-27T11:44:10.643 回答
4

这假设属性被命名为类。即 Type 的属性Foo也被命名为Foo。没有这个假设,问题就缺乏一些关键信息。

您可以使用该string.Split方法在点处分隔字符串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实例的引用。

于 2012-08-27T11:41:16.363 回答
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/

于 2012-08-27T11:36:59.520 回答
1

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

C# 反射:如何从字符串中获取类引用?

...然后使用您链接到的其余帖子从那里获取属性和价值:

通过字符串名称获取属性值

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

于 2012-08-27T11:38:29.553 回答