繁体   English   中英

在C#中有类似Python的getattr()吗?

[英]Is there something like Python's getattr() in C#?

在C#中有类似Python的getattr()吗? 我想通过读取一个包含要放在窗口上的控件名称的列表来创建一个窗口。

还有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");

为此使用反射。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM