在C#中有像Python's getattr()这样的东西吗?我想通过读取一个列表来创建一个窗口,该列表包含要放在窗口上的控件的名称。
发布于 2008-09-26 06:57:23
还有Type.InvokeMember。
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");发布于 2008-09-26 06:39:44
为此,请使用反射。
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);发布于 2008-09-26 06:40:58
是的,你能做到的.
typeof(YourObjectType).GetProperty("PropertyName").GetValue(instanceObjectToGetPropFrom, null);https://stackoverflow.com/questions/138045
复制相似问题