Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reflection class to get all properties of any object

Tags:

c#

reflection

I need to make a function that get all the properies of an object (including an children objects) This is for my error logging feature. Right now my code always returns 0 properties. Please let me know what I'm doing wrong, thanks!

public static string GetAllProperiesOfObject(object thisObject)
{
    string result = string.Empty;
    try
    {
        // get all public static properties of MyClass type
        PropertyInfo[] propertyInfos;
        propertyInfos = thisObject.GetType().GetProperties(BindingFlags.Public | BindingFlags.Static);//By default, it will return only public properties.
        // sort properties by name
        Array.Sort(propertyInfos,
                   (propertyInfo1, propertyInfo2) => propertyInfo1.Name.CompareTo(propertyInfo2.Name));

        // write property names
        StringBuilder sb = new StringBuilder();
        sb.Append("<hr />");
        foreach (PropertyInfo propertyInfo in propertyInfos)
        {
            sb.AppendFormat("Name: {0} | Value: {1} <br>", propertyInfo.Name, "Get Value");
        }
        sb.Append("<hr />");
        result = sb.ToString();
    }
    catch (Exception exception)
    {
        // to do log it
    }

    return result;
}

here's what the object looks like: alt textalt text

like image 918
aron Avatar asked Oct 26 '10 01:10

aron


People also ask

How does reflection set property value?

To set property values via Reflection, you must use the Type. GetProperty() method, then invoke the PropertyInfo. SetValue() method. The default overload that we used accepts the object in which to set the property value, the value itself, and an object array, which in our example is null.

How to get instance of an object in java?

The getInstance() method of java. security. Provider class is used to Returns a Signature object that implements the specified signature algorithm. A new Signature object encapsulating the SignatureSpi implementation from the specified Provider object is returned.


2 Answers

If you want all of the properties, try:

propertyInfos = thisObject.GetType().GetProperties(
      BindingFlags.Public | BindingFlags.NonPublic // Get public and non-public
    | BindingFlags.Static | BindingFlags.Instance  // Get instance + static
    | BindingFlags.FlattenHierarchy); // Search up the hierarchy

For details, see BindingFlags.

like image 120
Reed Copsey Avatar answered Oct 04 '22 16:10

Reed Copsey


The problem with your code is the PayPal Response types are members, NOT properties. Try:

MemberInfo[] memberInfos = 
    thisObject.GetMembers(BindingFlags.Public|BindingFlags.Static|BindingFlags.Instance);
like image 45
Law Metzler Avatar answered Oct 04 '22 16:10

Law Metzler