lundi 12 août 2019

Get the runtime type of a generic method parameter

I want to have a generic method with a random type parameter.

The instances of T shoud be a models with some attributed properties, so I whant to collect all public properties of an instance.

In additional I want to have an Interface or Superclass for the models and able to use other inheritance stuff on them too.

The problem is the typeof(T) result for models that have been passed as SuperClass or Interface explicitly does have no information about the subclasses.

public interface ISomeInterface { int IProperty { get; }  }

public class SomeClass : ISomeInterface 
{ 
    public int ClassProperty { get; set; } //I need this too

    public int IProperty { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var v = (ISomeInterface)new SomeClass();

        TestMethod(v);

        Console.ReadKey();
    }

    static void TestMethod<T>(T value) where T : ISomeInterface
    {
        var props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
        foreach (var p in props)
        {
            Console.WriteLine(p.Name);
        }
    }
}

The output will be the IProperty only, the ClassProperty had been missed.

I can not be shure that values always will have been passed in like subtypes explicitly in future.

Is there are any way to get the runtime type of an instance without using *.GetType() in this case, even for a null refferences?





Aucun commentaire:

Enregistrer un commentaire