简体   繁体   English

通用类型,该通用类型实现具有多个类型的通用接口

[英]generic type which implement a generic interface with more than one type

I have this interface: 我有这个界面:

interface a<A, B>
{
    A retA();
    B retB();
}

and I would like to create a generic method that takes a type which implements this interface. 并且我想创建一个通用方法 ,该方法采用实现此接口的类型。

private void fa<T>() where T : a<A, B>, new(){ code}

This line doesn't work ( compile time error ): 该行不起作用( 编译时错误 ):

the type or namespace A could not be found, the type or namespace B could not be found 找不到类型或名称空间A,找不到类型或名称空间B

Thank you for your help 谢谢您的帮助

You have three generic parameters ( A , B , T ) within fa method; fa方法中有三个通用参数( ABT ); each of them should be either declared or resolved ; 每个都应该被宣布解决 ; there are several ways to do it, eg 有几种方法可以做到这一点,例如

  public class Sample1<A, B> {
    // Class declares A and B; method declares T
    private void fa<T>() where T : a<A, B>, new() {
      // Code
    }
  }

  public class Sample2 {
    // Method declares all three generic types: A, B and T
    private void fa<T, A, B>() where T : a<A, B>, new() {
      // Code 
    }
  }

  public class Sample3 {
    // Method declares T; A and B are resolved (explict types: string and int)
    private void fa<T>() where T : a<string, int>, new() {
      // Code
    }
  }

  public class Sample4<A> {
    // Class declares A; method declares T; B is resolved (explicit type int)
    private void fa<T>() where T : a<A, int>, new() {
      // Code
    }
  }

Etc. 等等。

德米特里·拜琴科(Dmitry Bychenko)给出的答案:

fa<T, A, B>() where T : a<A, B>, new(){ code} 

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

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