簡體   English   中英

通過反射遞歸查找對象屬性?

[英]Recursively find object property via reflection?

假設我有課,

class A
{
  B PropA{get; set;}
}

class B
{
  string PropB{get; set;}
  C PropC{get; set;}
}

class C
{
  string PropD{get; set;}
}

現在我想獲取“ PropA.PropB”嗎? 同樣,我想獲取“ PropA.PropC.PropD”,依此類推嗎? 我需要創建一個將“ PropA.PropB”作為參數並返回PropetyInfo的方法。

static class Program
{
    static readonly BindingFlags flags = BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;

    static void Main() {
        var a = new A { PropA = new B() { PropB = "Value" } };
        var prop = GetPropertyRecursive("PropA.PropB", a);
    }

    static object GetPropertyRecursive(string property, object obj) {
        var splitted = property.Split('.');
        var value = obj.GetType().GetProperty(splitted[0], flags).GetValue(obj);

        if (value == null) {
            return null;
        }

        if (splitted.Length == 1) {
            return value;
        }

        return GetPropertyRecursive(string.Join(".", splitted.Skip(1)), value);
    }
}

假設我們不知道PropAPropC的屬性名稱,而只知道它們的類型,並且我們也知道目標類C中屬性string PropD的名稱:

class A
{
    public B PropA { get; set; }
}

class B
{
    public string PropB { get; set; }
    public C PropC { get; set; }
}

class C
{
    public string PropD { get; set; }
}

class Program
{
    static object GetPValue(Type propType, object obj)
    {
        return obj.GetType().GetProperties()
            .First(p => p.PropertyType == propType).GetValue(obj);
    }

    static object GetPValue(string name, object obj)
    {
        return obj.GetType().GetProperty(name).GetValue(obj);
    }

    static void Main(string[] args)
    {
        A a = new A();
        B b = new B();
        C c = new C();
        a.PropA = b;
        b.PropB = "B";
        b.PropC = c;
        c.PropD = "C";

        object obj = new object();

        obj = GetPValue(typeof(C), GetPValue(typeof(B), a));

        Console.WriteLine(GetPValue("PropD", obj));
    }
}

輸出: C

我已將您的媒體資源公開,以使以下示例起作用:

static void Main(string[] args)
{

    var propertyInfo = GetPropertyInfo(typeof(A), "PropA.PropC");
    Console.WriteLine(propertyInfo.Name);
    Console.ReadLine();
}

static PropertyInfo GetPropertyInfo(Type type, string propertyChain)
{
    if (!propertyChain.Contains("."))
    {
        var lastProperties = type.GetProperties().Where(m => m.Name.Equals(propertyChain));
        return lastProperties.Any() ? lastProperties.First() : null;
    }

    var startingName = propertyChain.Split('.')[0];
    var found = type.GetProperties().Where(m => m.Name.Equals(startingName));
    return found.Any() ? GetPropertyInfo(found.First().PropertyType, propertyChain.Replace(startingName + ".", "")) : null;
}

我不太明白你的問題...

如果要獲取類屬性的名稱,可以執行以下操作:

using System.Linq;
using System.Reflection;

List<Type> properties = GetTypesInNamespace(Assembly.GetExecutingAssembly(), "YourClassNameSpace");

 var propertiesNames = properties.Select(p => p.Name);

private List<Type> GetTypesInNamespace(Assembly assembly, string nameSpace)
{
    return assembly.GetTypes().Where(t => String.Equals(t.Namespace, nameSpace, StringComparison.Ordinal)).ToList();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM