lundi 29 avril 2019

C# Reflection on a Type Object

To clarify, yes, I do want to list the properties and values of a System.Type object, which is why I'm using "typeof(Type).GetProperties()" instead of "TheTypeObj.GetProperties()".

I'm trying to list all the property names and values of a Type object, but I'm getting an error. This is what I have so far:

using System.Reflection;

public static string list_properties(Type TheTypeObj)
{
    var Str = "\n";
    object Name, Value;
    foreach (var ThePropertyInfo in typeof(Type).GetProperties(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public))
    {
        Name = ThePropertyInfo.Name;
        Value = ThePropertyInfo.GetValue(TheTypeObj); //this line throws the error
        Str += Name + ": " + Value.ToString() + "\n";
    }
    return Str;
}

When I use it in context:

list_properties((new Object()).GetType());

I get this error:

Value = ThePropertyInfo.GetValue(TheTypeObj);

InvalidOperationException: Method may only be called on a Type for which Type.IsGenericParameter is true.

How do I list the properties and values of a Type object?





Aucun commentaire:

Enregistrer un commentaire