[英]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.