对对象属性的所有对象执行操作

时间:2015-05-18 09:20:36

标签: c#

是否可以在C#中表达这样的内容:

List<Object> l = null;
foreach (var property in this)            // Current Object
{
    l = property as List<Object>;

    if(null != l) l.Clear();
}

枚举所有属性的含义,如果属性指向类型为T的对象,则对其引用的对象执行操作foo()

3 个答案:

答案 0 :(得分:2)

是的,可以使用反射:

foreach (var property in this.GetType().GetProperties())
{
    var propVal = property.GetValue(this) as List<Object>;
    if (propVal != null)
    {
        propVal.Clear();
    }
}

答案 1 :(得分:1)

你可以得到这样的财产:

    public PropertyInfo GetProperty(string identifier)
    {
        return this.GetType().GetProperty(identifier);
    }

并通过这个获得所有属性:

    public PropertyInfo[] GetProperties()
    {
        return this.GetType().GetProperties();
    }

然后你可以使用foreach并获得值:

    var properties = this.GetProperties();

    foreach (var property in properties)
    {
        property.GetValue(this, null);
    }

您只需要在班级中实施此方法。

答案 2 :(得分:0)

public class MyClass
{
    public List<Object> MyList { get; set; }
    public MyClass myField;

    public MyClass()
    {
        this.MyList = new List<object>();
    }

    public void ClearLists()
    {
        foreach (var prop in this.GetType().GetProperties())
        {
            if (prop.PropertyType.FullName == typeof(List<Object>).FullName)
            {
                (prop.GetValue(this) as List<Object>).Clear();
            }
        }
    }

    public void FieldAction(Type fieldType, string methodName, params object[] parameters)
    {
        foreach (var field in this.GetType().GetFields())
        {
            if (field.FieldType.Equals(fieldType))
            {
                var val = field.GetValue(this);
                val.GetType().GetMethod(methodName).Invoke(val, parameters);
            }
        }
    }
}

public class Program
{
    public static void Main()
    {
        var c = new MyClass();
        c.MyList.Add(new Object());
        c.ClearLists();
        Console.WriteLine(c.MyList.Count.ToString()); // 0

        c.myField = new MyClass();
        c.myField.MyList.Add(new Object());

        c.FieldAction(typeof(MyClass), "ClearLists");
        Console.WriteLine(c.myField.MyList.Count.ToString()); // 0
    }
}