【问题标题】:C# parameters in interface [closed]接口中的 C# 参数
【发布时间】:2013-04-11 20:24:42
【问题描述】:
class Test {
    public Test(string name, string age) {
    }
}

interface ITest
        ????????

class Example: ITest {
    public Example(/* ... */) {
    }
}

那么我应该在我的界面中使用什么来在我的示例中使用与测试中相同的参数?

我想做什么:

  • 我有 3 个类:abc

  • 我希望我的 c 继承自 ab

但是 C# 不允许你这样做......所以我想使用一个接口。

编辑 我的课程是:

  • 学生(姓名、年龄、学业)
  • 教师(姓名、年龄、班级)
  • 在职学生/教师(姓名、年龄、学习/课程、付款)

所以我想在我的工作班中使用其他班级的方法。

【问题讨论】:

  • 您的问题非常不清楚。

标签: c# interface


【解决方案1】:

接口被用作继承它的类的契约。这意味着您希望接口公开的任何公共方法/属性也必须在继承的类中公开。

在上述情况下,您没有在接口中公开任何公共方法/属性。让我给你举个例子。

Interface ITest
{
   void AddPerson(string name, string age);
}

Interface IPerson
{
    string ReturnPersonsAge(string name);
}

/// This must expose the AddPerson method
/// This must also expose the ReturnPersonByAge method
class Example : ITest, IPerson
{
   Dictionary<string, string> people = new Dictionary<string, string>();

   void AddPerson(string name, string age)
   {
      people.Add(name, age);
   }

   string ReturnPersonsAge(string name)
   {
      return people[name];
   }
}

希望对您有所帮助,但请随时提出更多问题,以便我帮助缩小您的问题范围。

【讨论】:

  • 嘿,我想做什么:我有 3 个类 -> a、b 和 c 我希望我的 C 继承自 a 和 b。但是c#不允许你这样做......所以我想使用一个接口。
  • 我认为你不能继承超过 1 个类??
  • Sorry Multiple Inheritence is not allowed,但允许从多个INTERFACES继承,略有不同。见编辑。
  • 是的,我知道我必须使用接口 =D Ty 来回答您的问题
【解决方案2】:

接口不能定义构造函数。当然还有其他方法可以做到,这取决于您想要实现的目标。

【讨论】:

    【解决方案3】:
    Interface IAClass
    {
      void Add(string s);
    }
    Interface IBClass
    {
      void Delete(string m);
    }
    
    
    Class A: IAClass
    {
      void Add(string name)
    {
      // Your Logic
    }
    }
    
    Class B: IBClass
    {
      void Delete(string name)
    {
      // Your Logic
    }
    }
    
    Class C:IAClass,IBClass
    {
         void Add(string name)
    {
      // Your Logic
    }
    
     void Delete(string name)
    {
      // Your Logic
    }
    }
    

    【讨论】:

      【解决方案4】:

      您可以在界面中将它们作为属性公开

      Interface ITest
      {
      string Name{get;set;}
      string Age{get;set;}
      }
      

      【讨论】:

      • 如果我使用公共测试(params string[] 参数)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-15
      • 1970-01-01
      • 1970-01-01
      • 2015-07-01
      相关资源
      最近更新 更多