【问题标题】:Can a class implement multiple interface with same datamember name but different type? [duplicate]一个类可以实现具有相同数据成员名称但类型不同的多个接口吗? [复制]
【发布时间】:2013-05-05 22:13:13
【问题描述】:

我想知道是否有人可以建议一个类是否可以一次实现以下接口?

interface a1
{
   int mycount;
}

interface a2
{
   string mycount;
}

interface a3
{
   double mycount;
}

【问题讨论】:

  • 试过了吗?
  • 这些是属性,不是字段,对吧?
  • 这些是数据成员而不是方法。
  • @Alag20 - 接口不能包含数据成员。它们可能是属性。

标签: c# inheritance interface


【解决方案1】:

你的接口都不会编译,我假设它们是方法而不是字段。

实现具有冲突成员名的多个接口的唯一方法是使用显式实现:

interface a1
{
   int mycount();
}

interface a2
{
   string mycount();
}


class Foo : a1, a2
{
    int a1.mycount()     { ... }
    string a2.mycount()  { ... }


    // you can _only_ access them through an interface reference
    // even Bar members need to typecast 'this' to call these methods
    void Bar()
    {
         var x = mycount();               // Error, won't compile
         var y = (this as a2).mycount();  // Ok, y is a string
    }
}

【讨论】:

  • 谢谢亨克。这是假设您已将数据成员更改为方法,并且我知道此实现将起作用。我的问题是,在最近的一次采访中,我有同样的问题,但我的回答被拒绝了——来自不同接口的同名数据成员不可能继承到同一个类中。所以我想确认这是正确的。出于某种原因,面试官的想法不同,这让我完全糊涂了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-27
  • 1970-01-01
  • 2022-01-27
  • 2012-10-08
  • 1970-01-01
相关资源
最近更新 更多