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

时间:2008-09-26 06:35:30

标签: c# python user-interface

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

4 个答案:

答案 0 :(得分: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);
    }
}

可以使用:

object value = ReflectionExt.GetAttr(obj, "PropertyName");

或(作为扩展方法):

object value = obj.GetAttr("PropertyName");

答案 1 :(得分:3)

使用反射。

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);

答案 2 :(得分:1)

是的,你可以这样做......

typeof(YourObjectType).GetProperty("PropertyName").GetValue(instanceObjectToGetPropFrom, null);

答案 3 :(得分:0)

可以使用object.GetType()。GetProperties()创建System.Reflection.PropertyInfo类。这可以用于使用字符串探测对象的属性。 (对象方法,字段等存在类似的方法)

我认为这不会帮助你实现目标。您可能应该直接创建和操作对象。控件具有您可以设置的Name属性,例如。

相关问题