我需要遍历ASP.NET网页上的所有控件。在配置文件中,我有一个控件类型列表及其属性,我将以某种方式处理它们。现在,我感兴趣的是:如果我拥有的是字符串,即控件类型的名称和各自属性的名称,我怎样才能获得所需的属性。
以下是示例:在配置文件中,我有字符串:
controltype = "label" propertyname = "Text"
controltype = "Image" propertyname = "ToolTip".
所以我的代码中有这样的东西:
List<Control> controls = GiveMeControls();
foreach(Control control in controls)
{
// in getPropertyNameFromConfig(control) I get typename of control
// and returns corresponding property name from config type
string propertyName = getPropertyNameFromConfig(control);
string propertyValue = getPropertyValueFromProperty(control, propertyValue);
// !!! Don't know how to write getPropertyValueFromProperty.
}
有没有人知道如何开发getPropertyValueFromProperty()?
提前致谢,
DP
答案 0 :(得分:2)
以下示例实现应该满足您的要求:
static string getPropertyValueFromProperty(object control, string propertyName)
{
var controlType = control.GetType();
var property = controlType.GetProperty(propertyName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
if (property == null)
throw new InvalidOperationException(string.Format("Property “{0}” does not exist in type “{1}”.", propertyName, controlType.FullName));
if (property.PropertyType != typeof(string))
throw new InvalidOperationException(string.Format("Property “{0}” in type “{1}” does not have the type “string”.", propertyName, controlType.FullName));
return (string) property.GetValue(control, null);
}
如果您对此有何疑问,请随时在评论中提问。
答案 1 :(得分:1)
您必须使用Reflection API。有了它,您可以检查类型和locate the properties by name,然后使用属性从控件实例中获取值。