简体   繁体   中英

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

Is there something like Python's getattr() in C#? 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 .

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.

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.

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(). 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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