C # generating a generic parameter for an interface

I need help creating common parameters before the interface.

I have a prebaked code like this:

public interface InterFoo<T> {...}
public InterFoo<T> specialFoo<T>() where T : InterFoo<T> {...}
public InterFoo<T> regularFoo<T>() {...}

and I want to implement something like this

public InterFoo<T> adaptiveFoo<T>()
{
    if (T is InterFoo<T>)
        return specialFoo<T as InterFoo>();
    return regularFoo<T>();
}

at this moment I cannot find any solution so that everything is useful, thanks.

EDIT: initially the functions returned int, but it has a simpler solution incompatible with the purpose of the code, the functions have been changed to request a common type.

+4
source share
1 answer

The operators isand asare compiled only for types that, according to the compiler, can be null(types of valid values ​​or types of links).

IsAssignableFrom:

public int adaptiveFoo<T>()
{
  if (typeof(InterFoo<T>).IsAssignableFrom(typeof(T))
    return specialFoo<InterFoo>();
  return regularFoo<T>();
}

** , **

, , , ( ) , . :

:

public InterFoo<T> adaptiveFoo<T>()
{
  if (typeof(InterFoo<T>).IsAssignableFrom(typeof(T))
  {
    var method = typeof (Class1).GetMethod("specialFoo");
    var genericMethod = method.MakeGenericMethod(typeof(T));
    return (Interfoo<T>)method.Invoke(this, null);
  }

  return regularFoo<T>();
}
+5

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


All Articles