jeudi 13 juillet 2023

C# Recursion using reflection on a where type constrain

I'm trying to do recursion through a class but I can't see how I can invoke it with a type constrain.

My problem is mainly I don't know how to invoke the recursion and pass the property type on the Analyze call.

Here's my code:

public class recursor {
public string Analyze<T>() where T : class, new() 
    {

        StringBuilder sb = new StringBuilder();

        T t = new T();

        var propList = t.GetType().GetProperties();

        foreach (var prop in propList)
        {
            System.TypeCode propertyTypeCode = Type.GetTypeCode(prop.PropertyType);
            if (prop.PropertyType.IsClass)
            {
                // THIS IS WHAT I CAN'T FIGURE IT OUT
                // sb.Append(this.Analyze());
            }
            else
            {
                sb.Append("not a class");
            }
        }
        return sb.ToString();
    }
  }


  public class A {}
  public class B {}
  public class C {}
  
  public class _container {
    public A _a;
    public B _b;
    public C _c;
  }

  public void main() {

   var r = new recursor();
   var s = r.Analyze<_container>();

  }




Aucun commentaire:

Enregistrer un commentaire