从父用户控件获取属性值

时间:2014-03-28 13:57:38

标签: c# asp.net reflection .net-2.0

我想创建一个从父用户控件获取值的方法,但PropertyInfo无法从父控件获取值并抛出异常。我认为这是因为它不是对象的实际类型。

我使用的是.NET 2,因此我无法使用动态关键字。

有没有办法做到这一点?

    public object GetFromPar(Control parent, string propertyName, Type parentType)
    {
        while (parent != null)
        {
            if (parent.GetType().IsSubclassOf(parentType))
            {
                PropertyInfo info = parent.GetType().GetProperty(propertyName);
                return info.GetValue(parent, null);
            }
            else
            {
                parent = parent.Parent;
            }
        }

        return null;
    }

这就是我称之为这个功能的方式。

this.GetFromPar(this.Parent, "Name", typeof(InfoControl));

InfoControl是一个用户控件,它是LoginPanelControl(this)的父级。

提前谢谢。

1 个答案:

答案 0 :(得分:0)

PropertyInfo info = (typeof(parent.GetType())).GetProperty(propertyName);

如果您知道父类型,可以将其替换为parent.GetType()。

相关问题