[英]Is there something like Python's getattr() in C#?
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属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.