2012-01-18 91 views
5

我有一個工具生成的部分類。如何在派生類或通過部分類實現接口?

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屬性不是。

可以這樣做嗎?

+0

爲什麼你不能延伸Foo:IFoo,如果這是你要求的? – Tigran 2012-01-18 13:22:12

+0

@Tigran:我不能觸摸Foo.cs文件 – Ropstah 2012-01-18 13:28:26

+0

@DBM:如上所述elswhere ..''應該是公開的 – Ropstah 2012-01-18 13:36:30

回答

8

是什麼阻止您在另一個文件中再次執行此操作?

public partial class Foo : IFoo 
{ 
} 

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

或在新的類

public class FooExtended : Foo, IFoo 
{ 
} 

同樣,你將不需要實現Bar因爲美孚已經實現了它。

+0

我試過這個,但是這不能編譯... – Ropstah 2012-01-18 13:25:47

+1

部分類的選項有限制。您需要將該文件放在同一個程序集中。擴展類的選項應該普遍適用。什麼是編譯錯誤? – 2012-01-18 13:26:48

+0

無論如何你都不能重新實現Bar,除非它是虛擬的,所以這是正確的方法。 – Alex 2012-01-18 13:27:00

1

您可以爲Foo創建一個實現IFoo的分部類,但是Bar屬性不公開,它不起作用。

如果酒吧財產是公衆:

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

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

partial class Foo : IFoo 
{ 

} 
+0

請參閱我的@Tomislav Markovski,「酒吧」應該公開 – Ropstah 2012-01-18 13:36:05

1

由於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現在是公開的,有作爲BarFoo始終沒有實施更多的問題。

相關問題