Implementing an interface with a generic type that is less restrictive than the method I need to call

I am implementing an interface for embedding custom business logic in a framework using Microsoft Unity. My main problem is that the interface I need to implement defines the following method:

T InterfaceMethod<T>(); 

T has no limits. In my code, I need to call a method from another third-party library with a method signature

 T AnotherMethod<T>() where T: class; 

Type T is significant for AnotherMethod logic. Is there a way to call AnotherMethod<T>() in my implementation without using reflection? I obviously have to take an alternative action if T is a value type. Is there an autobox way to get around this?

+6
source share
3 answers

I do not think that what you are looking for is possible without thought. At best, you can just call AnotherMethod<object>() and format the result. But it really will work correctly if AnotherMethod T not important for your purposes.

+1
source

I'm not sure if this is exactly what you need, but it allows you to call AnotherMethod from InterfaceMethod without using reflection. However, it still uses Convert.ChangeType.

The idea is to implement a constrained generic class implementation (here Tin). Then you convert the unlimited type T of InterfaceMethod to Tin. Finally, you can call the AnotherMethod method with a limited type. The following works fine with strings.

 public interface ITest { T InterfaceMethod<T> (T arg); } public interface ITest2 { U AnotherMethod<U>(U arg) where U : class; } public class Test<Tin> : ITest, ITest2 where Tin : class { public T InterfaceMethod<T> (T arg) { Tin argU = arg as Tin; if (argU != null) { Tin resultU = AnotherMethod(argU); T resultT = (T)Convert.ChangeType(resultU,typeof(T)); return resultT; } return default(T); } public U AnotherMethod<U> (U arg) where U : class { return arg; } } 
+2
source

What others say is that you can go through such an object:

 public interface ITest { T InterfaceMethod<T>(T arg); } public interface IAnotherTest { U AnotherMethod<U>(U arg) where U : class; } public class Test : ITest { private IAnotherTest _ianothertest; public T InterfaceMethod<T>(T arg) { object argU = arg as object; if (argU != null) { object resultU = _ianothertest.AnotherMethod(argU); T resultT = (T)Convert.ChangeType(resultU, typeof(T)); return resultT; } return default(T); } } 
0
source

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


All Articles