2017-02-24 36 views
-3
public class Parent 
{ 
    public Child Child1 { get; set; } 
    public Child Child2 { get; set; } 
    public Child Child3 { get; set; } 
} 
public class Child 
{ 
    public string Name { get; set; } 
} 

對linq來說有點新鮮。Linq查詢獲取對象的變量值

想使用反射

下面

了檢索所有即Child1,CHILD2,Child3的名稱值是我可以從反射看到的樣子。

Parent p = new Parent();

p.Child1.GetType()。GetProperties()。ToList();

+0

我看到從下面父p中反射的方式=新Logic.Parent(); ()GetErpert1.GetType()。GetProperties()。ToList() –

回答

2

以下似乎適用於我。

class Parent 
{ 
    public Child Child1 { get; set; } 
    public Child Child2 { get; set; } 
    public Child Child3 { get; set; } 
} 

public class Child 
{ 
    public string Name { get; set; } 
} 

public class Tests 
{ 
    public void Test() 
    { 
     var parent = new Parent(); 
     parent.Child1 = new Child() { Name = "Child1" }; 
     parent.Child2 = new Child() { Name = "Child2" }; 
     parent.Child3 = new Child() { Name = "Child3" }; 

     var bindingFlags = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static; 

     var names = ""; 

     parent.GetType() 
      .GetProperties(bindingFlags) //Gets All Properties where the bindingFlags are matching 
      .Where(w => w.PropertyType == typeof(Child)) //Filters all properties to type of Child 
      .ForEach(property => //Then foreach Child Property 
      { 
       property.GetType() 
        .GetProperties(bindingFlags) //Gets All Properties where the bindingFlags are matching 
        .Where(w => w.Name == "Name") //Filters all properties to Name of 'Name' 
        .ForEach(value => //Then foreach found Property 
        { 
         names += value.GetValue(property); //Gets the Value of Name Property 
        }); 
      }); 
     Console.Write(names); 
    } 
} 

輸出 「Child1Child2Child3」

編輯:(短路版本)

parent.GetType() 
    .GetProperties(bindingFlags) 
    .Where(w => w.PropertyType == typeof(Child)) 
    .ForEach(property => property.GetType() 
     .GetProperties(bindingFlags) 
     .Where(w => w.Name == "Name") 
     .ForEach(value => names += value.GetValue(property))); 
+0

謝謝Mueui,但查詢涉及到它的反射(GetType() .GetProperties)...我只是看反射不涉及.. .. –