简体   繁体   English

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

[英]C# casting generic parameter to interface

I need help with casting generic paremetrs down to an interface. 我需要帮助将通用的paremetrs转换为接口。

I have 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 point I cant find any solution so anything would be helpful, thanks. 在这一点上,我无法找到任何解决方案,所以任何事情都会有所帮助,谢谢。

EDIT: originally the functions had returned an int but that has a simpler solution that is incompatible with the code's intended purpose, the functions have been changed to request a generic type. 编辑:最初函数返回了一个int但是有一个更简单的解决方案与代码的预期目的不兼容,函数已被更改为请求泛型类型。

The is and as operators only compile for types that the compiler knows can be null (nullable value types or reference types). isas运算符只编译编译器知道的类型可以为null (可空值类型或引用类型)。

You can try a call to IsAssignableFrom: 您可以尝试调用IsAssignableFrom:

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

** Update to reflect changes in question ** **更新以反映问题的变化**

Type constraints are, unfortunately viral, in order for your method to compile (when keeping with strict type checking from the compiler) you would need the constraint to be added to this method also. 不幸的是,类型约束是病毒式的,为了使您的方法能够编译(当保持编译器的严格类型检查时),您还需要将约束添加到此方法中。 However, reflection can circumvent this restriction: 但是,反思可以规避这种限制:

Your method would be: 你的方法是:

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>();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM