C# PropertyInfo用于属性链末端的属性

C# PropertyInfo用于属性链末端的属性,c#,reflection,C#,Reflection,我有这样的想法: class OriginalClass { public Type2 object2 { get; set; } } class Type2 { public Type3 object3 { get; set; } } class Type3 { public Type4 object4 { get; set; } } var obj = new OriginalClass(); var object4 = obj.object2.object3.

我有这样的想法:

class OriginalClass
{
    public Type2 object2 { get; set; }
}

class Type2
{
    public Type3 object3 { get; set; }
}

class Type3
{
    public Type4 object4 { get; set; }
}

var obj = new OriginalClass();
var object4 = obj.object2.object3.object4;
我还有一个字符串值: object2.object3.object4

这是通过object2和object3从类型T到object4的路径,这两个属性都返回对象。object4是object3上的属性


如何为最后一个property object4动态创建PropertyInfo对象?

您可以实现如下扩展方法:

public static class TypeExtensions
{
    /// <summary>Looks for a property using an object path where each
    /// property to match is accessed using dot syntax</summary>
    public static PropertyInfo GetPropertyByPath(this Type someType, string objectPath, BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public)
    {
        string[] objectPathParts = objectPath.Split('.');

        // #1 property in the object path should be obtained from T
        PropertyInfo currentProperty = someType.GetProperty(objectPathParts[0], bindingFlags);
        for (int propertyIndex = 1; propertyIndex < objectPathParts.Length; propertyIndex++)
        {
            // While all other association properties should be obtained
            // accessing PropertyInfo.PropertyType
            currentProperty = currentProperty.PropertyType.GetProperty(objectPathParts[propertyIndex], bindingFlags);
            if (currentProperty == null)
                throw new ArgumentException("Some property in the object path doesn't exist", "objectPath");
        }

        return currentProperty;
    }
}
方法2:使用表达式树。更好更简单! 您还可以使用较少的反射来解决此问题:

public static class ReflectionHelper
{
    public static PropertyInfo GetPropertyByPath<T>(Expression<Func<T, object>> pathExpr)
    {
        // It must be a member access expression like "x.y.z"
        MemberExpression propertyAccessExpr = pathExpr.Body as MemberExpression;

        // if it's not a member access expression, return null
        if(propertyAccessExpr == null)
            return null;

        return propertyAccessExpr.Member as PropertyInfo;
    }
}
然后获取路径中的最后一个属性信息,如下所示:

PropertyInfo object4Info = typeof(OriginalClass).GetPropertyByPath("object2.object3.object4");
PropertyInfo object4Info = ReflectionHelper
     .GetPropertyByPath<OriginalClass>(c => c.object2.object3.object4);

使用下面的代码,您可以执行以下操作:

PropertyInfo pi = GetPropertyInfoFromPath(obj.GetType(), "object2.object3.object4");
我仍然需要把这篇文章作为一块金块来发表,但这里是我的反射库的摘录

public static PropertyInfo GetPropertyInfoFromPath<T>(string path)
{
  var type = typeof(T);
  return GetPropertyInfoFromPath(type, path);
}

public static PropertyInfo GetPropertyInfoFromPath(Type type, string path)
{
  var parts = path.Split('.');
  var count = parts.Count();

  if (count == 0)
    throw new InvalidOperationException("Not a valid path");

  if (count == 1)
    return GetPropertyInformation(type, parts.First());
  else
  {
     var t = GetPropertyInformation(type, parts[0]).PropertyType;
     return GetPropertyInfoFromPath(t, string.Join(".", parts.Skip(1)));
  }
}

你的问题相当含糊。有趣的是object2的类型。你到底想解决什么问题?这看起来像一个.@ WaHalee让我们把它看作Obj.Objt2.Objut3.Objt4,其中OBJ是Type T.的一个实例。我想用RealthIdId编辑你的问题来包含最后一个属性Objist4的PrimeType信息对象,其中包括一些代码,我认为这些代码涵盖了你要问的内容。如果这不是你想要的,请随意回复,但我认为人们会尽力帮助你解决你的问题。我还编辑了你的标题“嵌套对象”表示嵌套类,即定义在另一个类中的类。
public static Type GetPropertyType<T>(Expression<Func<T, object>> expression)
    {
        var info = GetPropertyInformation(expression) as PropertyInfo;
        return info.PropertyType;
    }

    public static MemberInfo GetPropertyInformation<T>(Expression<Func<T, object>> propertyExpression)
    {
        return PropertyInformation(propertyExpression.Body);
    }

    public static PropertyInfo PropertyInformation(Expression propertyExpression)
    {
        MemberExpression memberExpr = propertyExpression as MemberExpression;
        if (memberExpr == null)
        {
            UnaryExpression unaryExpr = propertyExpression as UnaryExpression;
            if (unaryExpr != null && unaryExpr.NodeType == ExpressionType.Convert)
            {
                memberExpr = unaryExpr.Operand as MemberExpression;
            }
        }

        if (memberExpr != null)
        {
            var propertyMember = memberExpr.Member as PropertyInfo;
            if (propertyMember != null)
                return propertyMember;
        }

        return null;
    }
[Fact]
public void GetPropertyInfo_FromInstanceNestedPropertyUsingPathString_ReturnsPropertyInfo()
{
        var deepType = Helper.GetPropertyInfoFromPath<TestModel>("Nested.Deep");
        var deepDeclaringType = Helper.GetPropertyInfoFromPath<TestModel>("Nested");

        Assert.Equal(typeof(string), deepType.PropertyType);
        Assert.Equal(typeof(NestedModel), deepDeclaringType.PropertyType);
}
public class TestModel : Base
{
    public int Id { get; set; }

    [PickMe]
    public string MyString { get; set; }

    public NestedModel Nested { get; set; }
    public DateTime ClosedAt { get; set; }
}

public class NestedModel
{
    public string Deep { get; set; }
}