【问题标题】:How can I use a parameter in an interface that is defined by the interface如何在接口定义的接口中使用参数
【发布时间】:2014-09-07 12:51:55
【问题描述】:

我尝试定义这样的接口:

public interface Something
{
   void f();
}
public interface SomethingElse
{
   void g(Something s);
}

这应该说 g 接受一个与接口“Something”相关的参数。当我尝试创建类时,编译器将拒绝 SomethingElse 类,因为它与接口定义的签名不匹配。但是我应该如何定义接口呢?

class Something_class : Something
{
   public void f() { Console.WriteLine("Something.f"); }
}
class SomethingElse_class : SomethingElse
{
   public void g(Something_class s) { Console.WriteLine("SomethingElse.g"); }
}

【问题讨论】:

  • 只需在 SomethingElse_class 中使用 void g(Something s)。

标签: c#


【解决方案1】:

您的SomethingElse 接口表明任何实现都需要接受实现Somethingany 类型——而不仅仅是一个具体示例。

要么您需要将SomethingElse_class 更改为:

class SomethingElse_class : SomethingElse
{
   public void g(Something s) { Console.WriteLine("SomethingElse.g"); }
}

... 或将SomethingElse 设为通用,例如

public interface SomethingElse<T> where T : Something
{
   void g(T s);
}

那么SomethingElse_class 将是:

class SomethingElse_class : SomethingElse<Something_class>
{
   public void g(Something_class s) { ... }
}

【讨论】:

    【解决方案2】:
           class SomethingElse_class : SomethingElse
            {
                public void g(Something_class s)
                {
                    Console.WriteLine("SomethingElse.g");
                }
                public void g(Something s) //overload g with the (Something s)
                {
                    Console.WriteLine("Something.g");
                }
            }
    

    【讨论】:

      猜你喜欢
      • 2012-10-28
      • 1970-01-01
      • 1970-01-01
      • 2011-04-10
      • 1970-01-01
      • 2014-01-14
      • 2014-10-15
      • 2021-01-27
      • 1970-01-01
      相关资源
      最近更新 更多