在类 Person 中,我与类 Position 相关,类 Position 与类 PositionTitle 相关,并且 PositionTitle 有一个名为 Title 的属性
public class Person
{
public position Position{get;set;}
public string Name{get;set;}
public DateTime BirthDate{get;set;}
public bool IsAdmin{get;set;}
public int Age{get;set;}
}
public class position
{
public positionTitle PositionTitle{get;set;}
public bool IsSystem{get;set;}
}
public class PositionTitle
{
public string Title{get;set;}
}
Run Code Online (Sandbox Code Playgroud)
我有一个字符串“Person.Position.PositionTitle.Title”,我怎样才能用这个字符串获取person的这个属性?
编辑:
我应该添加一些东西,我要获取人员的所有属性,直到进入系统类型,我的意思是我想将这些属性作为字符串{Name,Age,IsAdmin,BirthDate,IsSystem,Title}
我怎么能?
EDiT2:还有一个问题,Position 本身可以与 Person 相关,如果我获取 person 的属性并递归地获取与 Person 相关的那些类的属性,将会出现一个不间断的循环,因为 Person 有一个职位和职位都有人
基本上,您用“.”分割字符串,然后循环遍历每个子字符串,使用反射来获取当前实例的属性。然后将实例设置为您刚刚获得的属性。
您最终会得到您想要的财产。
/// <summary>
/// Gets an object property's value, recursively traversing it's properties if needed.
/// </summary>
/// <param name="FrameObject">The object.</param>
/// <param name="PropertyString">The object property string.
/// Can be the property of a property. e.g. Position.X</param>
/// <returns>The value of this object's property.</returns>
private object GetObjectPropertyValue(Object FrameObject, string PropertyString)
{
object Result = FrameObject;
string[] Properties = PropertyString.Split('.');
foreach (var Property in Properties)
{
Result = Result.GetType().GetProperty(Property).GetValue(Result, null);
}
return Result;
}
Run Code Online (Sandbox Code Playgroud)
免责声明:这适用于我的使用,请注意空引用等!