Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 961
Andre Avatar asked Sep 26 '08 06:09

Andre


People also ask

Is Getattr () used for?

Python getattr() function is used to access the attribute value of an object and also gives an option of executing the default value in case of unavailability of the key.

Is Getattr a python?

Python getattr() function is a built-in function used to access the attribute value of an object. It is also used to execute the default value in case the attribute/key does not exist.

What would happen if Getattr () tried to retrieve an attribute of an object that did not exist?

The getattr() method returns the value of the named attribute of an object. If not found, it returns the default value provided to the function.

What does __ Getattr __ do in Python?

__getattr__(self, name) Is an object method that is called if the object's properties are not found. This method should return the property value or throw AttributeError . Note that if the object property can be found through the normal mechanism, it will not be called.


2 Answers

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");
like image 169
Brannon Avatar answered Oct 10 '22 14:10

Brannon


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);
like image 31
Eric Schoonover Avatar answered Oct 10 '22 15:10

Eric Schoonover