【发布时间】:2008-09-26 06:35:30
【问题描述】:
C# 中有类似Python's getattr() 的东西吗?我想通过读取包含要放在窗口上的控件名称的列表来创建一个窗口。
【问题讨论】:
标签: c# python user-interface
C# 中有类似Python's getattr() 的东西吗?我想通过读取包含要放在窗口上的控件名称的列表来创建一个窗口。
【问题讨论】:
标签: c# python user-interface
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");
【讨论】:
为此使用反射。
Type.GetProperty() 和 Type.GetProperties() 分别返回 PropertyInfo 实例,可用于读取对象的属性值。
var result = typeof(DateTime).GetProperty("Year").GetValue(dt, null)
Type.GetMethod() 和Type.GetMethods() 各自返回MethodInfo 实例,可用于对对象执行方法。
var result = typeof(DateTime).GetMethod("ToLongDateString").Invoke(dt, null);
如果您不一定知道类型(如果您新属性名称会有点奇怪),那么您也可以这样做。
var result = dt.GetType().GetProperty("Year").Invoke(dt, null);
【讨论】:
是的,你可以这样做...
typeof(YourObjectType).GetProperty("PropertyName").GetValue(instanceObjectToGetPropFrom, null);
【讨论】:
可以使用 object.GetType().GetProperties() 创建 System.Reflection.PropertyInfo 类。这可用于使用字符串探测对象的属性。 (对象方法、字段等也存在类似的方法)
但我认为这不会帮助您实现目标。您可能应该直接创建和操作对象。例如,控件具有您可以设置的 Name 属性。
【讨论】: