开发者

how to get property of entity of entity by name

in class Person i have relation to class Position, and the class Position has a relat开发者_Python百科ion to class PositionTitle, and the PositionTitle has a property named 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;}
}

i have a string "Person.Position.PositionTitle.Title", how can i get this property of person with this string??

EDIT:

i should add sth, im gonna get all properties of person till getting to system types,, i mean i wanna have these propertis as string { Name,Age,IsAdmin,BirthDate,IsSystem,Title}

how could I?

EDiT2: one more problem,, Position itself can have a relation to Person, and if i get properties of person and recursively get properties of those classes that person have a relation to,, there would be a non stop loop, because Person has a Position and Position has a Person


Basically you split the string by the '.', then loop through each substring, using reflection to get the property of the current instance. Then set the instance to the property you've just got.

You'll end up with the property you're after.

    /// <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;
    }

Disclamer: This works for my use, watch out for null references etc!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜