如何访问子类属性?,我可以访问 Y 属性,在这种情况下是名称,但不是 x,另一种情况是相同的,但不是 x 的单个引用,而是带有 x 的列表,在第二种情况下,如何迭代每个对象.
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));
}
}
更新
也试试界面
public interface ISub
{}
public class X : ISub // etc....
if (typeof(ISub).IsAssignableFrom(property.GetType()) ) // this alwas as false