C#将通用参数转换为接口

ben*_*iii 4 c# generics types casting generic-constraints

我需要帮助将通用的paremetrs转换为接口.

我有这样的预烘焙代码:

public interface InterFoo<T> {...}
public InterFoo<T> specialFoo<T>() where T : InterFoo<T> {...}
public InterFoo<T> regularFoo<T>() {...}
Run Code Online (Sandbox Code Playgroud)

我想实现这样的东西

public InterFoo<T> adaptiveFoo<T>()
{
    if (T is InterFoo<T>)
        return specialFoo<T as InterFoo>();
    return regularFoo<T>();
}
Run Code Online (Sandbox Code Playgroud)

在这一点上,我无法找到任何解决方案,所以任何事情都会有所帮助,谢谢.

编辑:最初函数返回了一个int但是有一个更简单的解决方案与代码的预期目的不兼容,函数已被更改为请求泛型类型.

Ric*_*lly 5

isas运营商仅编译该编译器知道可以是类型null(空值类型或引用类型).

您可以尝试调用IsAssignableFrom:

public int adaptiveFoo<T>()
{
  if (typeof(InterFoo<T>).IsAssignableFrom(typeof(T))
    return specialFoo<InterFoo>();
  return regularFoo<T>();
}
Run Code Online (Sandbox Code Playgroud)

**更新以反映问题的变化**

不幸的是,类型约束是病毒式的,为了使您的方法能够编译(当保持编译器的严格类型检查时),您还需要将约束添加到此方法中.但是,反思可以规避这种限制:

你的方法是:

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>();
}
Run Code Online (Sandbox Code Playgroud)