0

how can access sub class properties?, I can access Y properties, in this case Name, but not x, another case is the same but instead of single reference of x, with a list of x, in this second case how iterate every object.

    public class X
{
    public int ID{get;set;} 
    public int Name{get;set;}
}

public class y
{

    public string Name{get;set;}
    public x Reference{get:set;}
}

    //second case 
public class y
{

    public string Name{get;set;}
    public List<x> Reference{get:set;}
}



public static void Main()
{
    y classY = new y();
    y.Name = "some text here";
    y.x.ID = "1";
    y.x.Name ="some text for x here";
}

// in another class, pass y
// so, in this method I only can get 'y' values, but not x
Hashtable table = new Hashtable();
public void GetProperties(object p)
{
    Type mytype = p.GetType();
    var properties = mytype.GetProperties(BindingFlags.Public | BindingFlags.Instance);

    foreach (var property in properties)
    {
        table.Add(property.Name, property.GetValue(p, null));
    }   
}

UPDATE

Also try with interface

public interface ISub
{}
public class X : ISub // etc....


if (typeof(ISub).IsAssignableFrom(property.GetType()) ) // this alwas as false 
Crashman
  • 146
  • 11
  • You want to obtain properties only for used types defined in your assembly? How would you handle it if `y` had a reference to `x` and `x` had a property of type `y`? – e_ne Jan 14 '13 at 17:09
  • Because the object's contains descendant reference, – Crashman Jan 14 '13 at 17:47

1 Answers1

0

You will have to evaluate each property to know if it is a list or not:

foreach (var prop in properties)
{
    var obj = prop.GetValue(p, null);
    if (obj is List<x>)
    {
        var list = obj as List<x>;
        // do something with your list
    }
    else
    {
        table.Add(prop.Name, obj);
    }
}   
lante
  • 7,192
  • 4
  • 37
  • 57