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

And*_*dre 13 c# python user-interface

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

Bra*_*non 9

还有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);
    }
}
Run Code Online (Sandbox Code Playgroud)

可以使用如下:

object value = ReflectionExt.GetAttr(obj, "PropertyName");
Run Code Online (Sandbox Code Playgroud)

或(作为扩展方法):

object value = obj.GetAttr("PropertyName");
Run Code Online (Sandbox Code Playgroud)


Eri*_*ver 5

为此使用反射。

Type.GetProperty()Type.GetProperties()每个返回PropertyInfo的情况下,其可以被用来读取物体上的属性值。

var result = typeof(DateTime).GetProperty("Year").GetValue(dt, null)
Run Code Online (Sandbox Code Playgroud)

Type.GetMethod()并且Type.GetMethods()每个返回MethodInfo实例,可用于在对象上执行方法。

var result = typeof(DateTime).GetMethod("ToLongDateString").Invoke(dt, null);
Run Code Online (Sandbox Code Playgroud)

如果您不一定知道类型(如果您更新属性名称会有点奇怪),那么您也可以执行类似的操作。

var result = dt.GetType().GetProperty("Year").Invoke(dt, null);
Run Code Online (Sandbox Code Playgroud)