簡體   English   中英

如何在派生類或部分類中實現接口?

[英]How to implement interface in derived class or through partial classes?

我有一個由工具生成的部分類。

Foo.cs

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

我需要在不觸及Foo.cs的情況下為Foo實現以下接口:

IFoo.cs

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

擴展Foo也是一種選擇,但重新實現Bar屬性不是。

可以這樣做嗎?

是什么阻止你在另一個文件中再次這樣做?

public partial class Foo : IFoo
{
}

由於Bar屬性已經存在,因此不需要重新實現它。

或者在新課堂上

public class FooExtended : Foo, IFoo
{
}

同樣,你不需要實現Bar因為Foo已經實現了它。

你可以為Foo創建一個實現IFoo的部分類,但是Bar屬性不是公共的,它將無法工作。

如果Bar屬性是公開的:

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

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

partial class Foo : IFoo
{

}

由於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實現。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM