C # Reflection using MakeGenericMethod method with a method that has a constraint like 'new ()'

I am trying to use MethodInfo MakeGenericMethod as follows:

        foreach (var type in types)
        {
            object output = null;
            var method = typeof (ContentTypeResolver).GetMethod("TryConstruct");
            var genmethod = method.MakeGenericMethod(type);
            var arr = new object[] { from, output };
            if ((bool)genmethod.Invoke(null, arr))
                return (IThingy)arr[1];
        }

Against the following general method:

    public static bool TryConstruct<T>(string from, out IThingy result) where T : IThingy, new()
    {
        var thing = new T();
        return thingTryConstructFrom(from, out result);
    }

The problem is that I get an argument exception on the MakeGenericMethod line, because the type I'm passing is not "new ()"

Is there any way around this? Thanks

+3
source share
1 answer

. TryConstruct , IThingy new. TryConstruct: , TryConstruct new T()? T(), .

, , MakeGenericMethod. nondefault, TryConstruct, , , Activator.CreateInstance new T().

+5

Source: https://habr.com/ru/post/1735335/


All Articles