开发者

I need to get the value from Nested Property

I need to get the value from nested property.

In MainClass i have a Students Property which is Type of Student Class.

MainClass obj = new MainClass ();

obj.Name = "XII";
obj.Students = new List<Students>()
    {
        new Students() { ID = "a0", Name = "A" },
        new Bridge() { ID = "a1", Name = "B" }
    };

Type t = Type.GetType(obj.ToString());
PropertyInfo p = t.GetProperty("Students");

object gg = p.GetValue(obj, null);
var hh = gg.GetType();
string propertyType = string.Empty;

if (hh.IsGenericType)
    {
        string[] propertyTypes = hh.ToString().Split('[');
        Type gggg = Type.GetType(propertyTypes[1].Remove(propertyTypes[1].Length - 1));
        foreach (PropertyInfo pro in gggg.GetProperties())
             开发者_运维问答{
                 if (pro.Name.Equals("Name"))
                 {
                     // Get the value here
                 }
             }
    } 


First of all,

Type t = Type.GetType(obj.ToString());

is wrong. This only works if a class has not overloaded the ToString() method, and will fall at runtime if it has. Fortunately, every class has a GetType() metod (it's defined on object, so Type t = obj.GetType() is the correct code.

Second, the

string[] propertyTypes = hh.ToString().Split('[');
Type gggg = Type.GetType(propertyTypes[1].Remove(propertyTypes[1].Length - 1)

is an awful way to get the type the specified the generic type, as there is a method GetGenericArguments that does that for you, so this code could be changed with

Type[] genericArguments = hh.GetGenericArguments();
Type gggg = genericArguments[0];

And now to the real problem, accessing an list item. The best way to do that is to use the indexer ([]) of the List<> class. In c# when you define an indexer, it's automatically transfered to a property called Item, and we can use that property to extract our values (the Item name can be inferred from the type definition, but for the most part, that can be hardcoded)

PropertyInfo indexer = hh.GetProperty("Item");  // gets the indexer

//note the second parameter, that's the index
object student1 = indexer.GetValue(gg, new object[]{0}); 
object student2 = indexer.GetValue(gg, new object[]{1}); 

PropertyInfo name = gggg.GetProperty("Name");
object studentsName1 = name.GetValue(student1, null); // returns "A"
object studentsName2 = name.GetValue(student2, null); // returns "B"


Override Equals method for both Students and Bridge class then use Find or use LINQ

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜