C# 从父用户控件获取属性值
我想创建一个从父用户控件获取值的方法,但是C# 从父用户控件获取属性值,c#,asp.net,reflection,.net-2.0,C#,Asp.net,Reflection,.net 2.0,我想创建一个从父用户控件获取值的方法,但是PropertyInfo无法从父控件获取值并引发异常。我认为这是因为它不是对象的实际类型 我正在使用.NET2,因此无法使用动态关键字 有没有办法做到这一点 public object GetFromPar(Control parent, string propertyName, Type parentType) { while (parent != null) { if (pare
PropertyInfo
无法从父控件获取值并引发异常。我认为这是因为它不是对象的实际类型
我正在使用.NET2,因此无法使用动态关键字
有没有办法做到这一点
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(此)的父级用户控件
先谢谢你
PropertyInfo info = (typeof(parent.GetType())).GetProperty(propertyName);
如果您知道父对象的类型,则可以将其替换为parent.GetType()。您确实存在哪些异常。异常:TargetInvocationException InnerException:指定的强制转换无效。@LastFrog发生异常的行是什么?它发生在info.GetValue(parent,null)中;你能说明你是如何调用这个方法的吗?我只是用一个基本的
Form
用下面的语法进行了尝试,效果很好:GetFromPar(这个“名称”,typeof(Form))代码>父级没有GetProperty()。这不是问题。你的意思是我可以这样做“parent.GetType().GetProperty(propertyName);”对吗?但我不能通过“info.GetValue(parent,null);”来获取值。我想这是因为类型不同,它可能会将父对象视为控件而不是InfoPanel。我的意思是你可以尝试:PropertyInfo=(typeof(ParentType)).GetProperty(propertyName);