繁体   English   中英

反射特性

[英]Properties by reflection

如何访问子类属性?在这种情况下,我可以访问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 

您将必须评估每个属性,以了解它是否为列表:

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);
    }
}   

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM