简体   繁体   English

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

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

Is there something like Python's getattr() in C#? 在C#中有类似Python的getattr()吗? I would like to create a window by reading a list which contains the names of controls to put on the window. 我想通过读取一个包含要放在窗口上的控件名称的列表来创建一个窗口。

There is also Type.InvokeMember . 还有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);
    }
}

Which could be used like: 可以使用如下:

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

or (as an extension method): 或(作为扩展方法):

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

Use reflection for this. 为此使用反射。

Type.GetProperty() and Type.GetProperties() each return PropertyInfo instances, which can be used to read a property value on an object. Type.GetProperty()Type.GetProperties()每个都返回PropertyInfo实例,可用于读取对象的属性值。

var result = typeof(DateTime).GetProperty("Year").GetValue(dt, null)

Type.GetMethod() and Type.GetMethods() each return MethodInfo instances, which can be used to execute a method on an object. Type.GetMethod()Type.GetMethods()每个都返回MethodInfo实例,可用于在对象上执行方法。

var result = typeof(DateTime).GetMethod("ToLongDateString").Invoke(dt, null);

If you don't necessarily know the type (which would be a little wierd if you new the property name), than you could do something like this as well. 如果您不一定知道类型(如果您新建了属性名称会有点奇怪),那么您也可以做类似的事情。

var result = dt.GetType().GetProperty("Year").Invoke(dt, null);

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

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

There's the System.Reflection.PropertyInfo class that can be created using object.GetType().GetProperties(). 可以使用object.GetType()。GetProperties()创建System.Reflection.PropertyInfo类。 That can be used to probe an object's properties using strings. 这可以用于使用字符串探测对象的属性。 (Similar methods exist for object methods, fields, etc.) (对象方法,字段等存在类似的方法)

I don't think that will help you accomplish your goals though. 我认为这不会帮助你实现目标。 You should probably just create and manipulate the objects directly. 您可能应该直接创建和操作对象。 Controls have a Name property that you can set, for example. 例如,控件具有您可以设置的Name属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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