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

C#将通用参数转换为接口,c#,generics,types,casting,generic-constraints,C#,Generics,Types,Casting,Generic Constraints,我需要帮助将通用参数转换为接口 我预编了如下代码: public interface InterFoo<T> {...} public InterFoo<T> specialFoo<T>() where T : InterFoo<T> {...} public InterFoo<T> regularFoo<T>() {...} public InterFoo接口{…} public InterFoo specialFoo(

我需要帮助将通用参数转换为接口

我预编了如下代码:

public interface InterFoo<T> {...}
public InterFoo<T> specialFoo<T>() where T : InterFoo<T> {...}
public InterFoo<T> regularFoo<T>() {...}
public InterFoo接口{…}
public InterFoo specialFoo(),其中T:InterFoo{…}
公共InterFoo regularFoo(){…}
我想实现这样的东西

public InterFoo<T> adaptiveFoo<T>()
{
    if (T is InterFoo<T>)
        return specialFoo<T as InterFoo>();
    return regularFoo<T>();
}
public-InterFoo-adaptiveFoo()
{
if(T是InterFoo)
返回specialFoo();
返回regularFoo();
}
在这一点上,我找不到任何解决方案,所以任何事情都将是有益的,谢谢


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

is和
as
运算符只编译编译器知道可以为
null
的类型(可为null的值类型或引用类型)

您可以从以下位置尝试调用IsAssignables:

public int adaptiveFoo<T>()
{
  if (typeof(InterFoo<T>).IsAssignableFrom(typeof(T))
    return specialFoo<InterFoo>();
  return regularFoo<T>();
}
public int adaptiveFoo()
{
if(typeof(InterFoo).IsAssignableFrom(typeof(T))
返回specialFoo();
返回regularFoo();
}
**更新以反映相关变更**

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

你的方法是:

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>();
}
public-InterFoo-adaptiveFoo()
{
if(typeof(InterFoo).IsAssignableFrom(typeof(T))
{
var方法=typeof(Class1).GetMethod(“specialFoo”);
var genericMethod=method.MakeGenericMethod(typeof(T));
return(Interfoo)方法。Invoke(this,null);
}
返回regularFoo();
}

感谢您的快速响应,不幸的是,我过于简化了示例代码。事实上,我需要函数返回Interfoo类型,这与specialfoo()将返回的Interfoo不兼容。(我已将更改合并到原始问题中)@问题是,为了让specialFoo通过泛型约束,InterFoo必须实现InterFoo(因为从约束的角度来看,要检查的类型T是InterFoo)@elgonzo Google,用于奇怪的递归模板模式(简称CRTP)Eric Lippert写了一篇很好的博文,我撤销了我的第一条评论。天啊,specialFoo方法的类型参数必须是
class a:InterFoo
type。哦,我的大脑受伤了。。。