C中是否有类似Python's getattr()的内容?我想通过读取包含要放在窗口上的控件名称的列表来创建一个窗口。
最佳答案
public static class ReflectionExt
{
public static object GetAttr(this object obj, string name)
{
Type type = obj.GetType();
BindingFlags flags = BindingFlags.Instance |
BindingFlags.Public |
BindingFlags.GetProperty;
return type.InvokeMember(name, flags, Type.DefaultBinder, obj, null);
}
}
可以像这样使用:
object value = ReflectionExt.GetAttr(obj, "PropertyName");
或(作为扩展方法):
object value = obj.GetAttr("PropertyName");