【问题标题】:How to implement interface in derived class or through partial classes?如何在派生类或通过部分类实现接口?
【发布时间】:2012-01-18 13:19:25
【问题描述】:

我有一个由工具生成的部分类。

Foo.cs

public partial class Foo {
    [SomeAttribute()]
    public string Bar {get;set;}
}

我需要为Foo 实现以下接口而不接触Foo.cs:

IFoo.cs

public interface IFoo {
    string Bar {get;set;}
}

扩展 Foo 也是一种选择,但重新实现 Bar 属性不是。

可以这样做吗?

【问题讨论】:

  • 为什么不能扩展 Foo:IFoo,如果这是你想要的?
  • @Tigran:我无法触摸 Foo.cs 文件
  • @DBM: 如其他地方所述.. Bar 应该是公开的

标签: c# oop interface


【解决方案1】:

是什么阻止您在另一个文件中再次执行此操作?

public partial class Foo : IFoo
{
}

由于Bar 属性已经存在,因此不需要重新实现它。

或者在一个新的类中

public class FooExtended : Foo, IFoo
{
}

同样,您不需要实现 Bar,因为 Foo 已经实现了它。

【讨论】:

  • 部分类的选项有限制。您需要将文件放在同一个程序集中。扩展类的选项应该通用。什么是编译错误?
  • 无论如何你都不能重新实现 Bar,除非它是虚拟的,所以这是正确的做法。
  • 错误是什么?它应该工作我以前做过。请注意,其他部分类文件需要在同一个命名空间中。
  • 'FooExtended' 没有实现接口成员'IFoo.Bar'
  • @DBM:我的错,Bar 是公开的!
【解决方案2】:

您可以为 Foo 创建一个实现 IFoo 的部分类,但如果 Bar 属性不是公共的,它将无法工作。

如果 Bar 属性是公开的:

partial class Foo
{
    public string Bar { get; set; }
}

interface IFoo
{
    string Bar { get; set; }
}

partial class Foo : IFoo
{

}

【讨论】:

  • 请看我的@Tomislav Markovski,Bar 应该是公开的
【解决方案3】:

由于Bar 是私有的,这就是您要查找的内容:

public partial class Foo : IFoo
{
    string IFoo.Bar
    {
        get
        {
            return this.Bar;  // Returns the private value of your existing Bar private field
        }
        set
        {
            this.Bar = value;
        }
    }
}

无论如何,这很令人困惑,应尽可能避免。

编辑:好的,你已经改变了你的问题,所以Bar现在是公开的,没有更多的问题,因为Bar总是在Foo中实现。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-17
    • 2010-09-22
    • 1970-01-01
    • 1970-01-01
    • 2015-01-05
    • 2014-09-04
    • 1970-01-01
    相关资源
    最近更新 更多