2011-06-21 56 views
2

类人获得实体的分财产,我有关系的阶级地位和阶级地位有关系类POSITIONTITLE和POSITIONTITLE有一个属性名为标题如何通过名称

public class Person 
{ 
    public Position Position{get;set;} 
} 

public class Position 
{ 
    public PositionTitle PositionTitle{get;set;} 
} 

public class PositionTitle 
{ 
    public string Title{get;set;} 
} 

我有一个字符串“Person.Position.PositionTitle.Title”,我怎样才能得到这个人与这个字符串的属性?

回答

6

您需要按点分割字符串,然后使用反射按名称获取每个属性。您可以使用PropertyInfo.PropertyType获得类型的 - 然后使用它来获取链中的下一个属性。事情是这样的:

public object GetProperty(object source, string path) 
{ 
    string[] bits = path.Split('.'); 
    Type type = source.GetType(); // Or pass this in 
    object result = source; 
    foreach (string bit in bits) 
    { 
     PropertyInfo prop = type.GetProperty(bit); 
     type = prop.PropertyType; 
     result = prop.GetValue(result, null); 
    } 
    return result; 
} 

您可能需要调整这个绑定标志等,但它是正确的基本理念。

+1

这是可能的,你要处理空值,要么抛出一个异常(所以你得到一个'NullReferenceException'而不是一个神秘的'TargetException')或返回'一旦你得到一个'null'。 – Gabe

+0

@加贝:是的,很有可能。我把它包含在“etc”中:) –

+0

对我来说,捕捉子属性的类型非常有用。 –

1

随着使用的System.Reflection:

s = "Person.Position.PositionTitle.Title"; 

string[] split = s.Split("."); 
int i = 0; 

Type t = Type.GetType(split[0]); 

object obj = null; 

for (i=0; i < split.Count()-1; i++) 
{ 
    PropertyInfo pi = t.getProperty(split[i+1]); 
    pi.getValue(obj, null); 
    t = pi.PropertyType(); 
} 

result = (string)obj;