2010-08-11 52 views
1

我在嘗試實現由linq2sql設計器創建的兩個類之間的共享方法/屬性時遇到了問題。LINQ2SQL中用於共享常用方法的抽象類

我的兩個班有兩個主要特性(從DB模式來):

public partial class DirectorPoll 
{ 
    public bool Completed {get; set;} 
    public bool? Reopen { get; set; } 
    //more properties 
} 

public partial class StudentPoll 
{ 
    public bool Completed {get; set;} 
    public bool? Reopen { get; set; } 
    //more properties 
} 

現在比如我創建一個抽象類:

public abstract class GenericPoll 
{ 
    public abstract bool Completed { get; set; } 
    public abstract bool? Reopen { get; set; } 

    public bool CanEdit 
    { 
     get 
     { 
      if (Completed == false) return true; 
      if (Reopen.GetValueOrDefault(false) == false) return false; 
      return true; 
     } 
    } 
} 

然後

public partial class DirectorPoll : GenericPoll 
public partial class StudentPoll: GenericPoll 

但是當我嘗試編譯它時說「Director不實現繼承的抽象成員GenericPoll.Completed 。得到」。但它在那裏。所以我想我不得不重寫設計器自動生成的屬性,但如果稍後更新數據庫並重新編譯,它會給我同樣的錯誤。

我想我可能會錯過這裏的東西,但我嘗試過不同的方法,但沒有成功。那麼除了在每個部分類中實現CanEdit之外,我還能在這裏做些什麼?謝謝

回答

2

它不是實現爲override,所以它不計數。然而,隱式接口實現計數,所以此工程:

partial class DirectorPoll : IGenericPoll {} 
partial class StudentPoll : IGenericPoll {} 
public interface IGenericPoll 
{ 
    bool Completed { get; set; } 
    bool? Reopen { get; set; } 
} 
public static class GenericPoll { 
    public static bool CanEdit(this IGenericPoll instance) 
    { 
     return !instance.Completed || instance.Reopen.GetValueOrDefault(); 
    } 
} 
+2

我們是Graveet的Borg。害怕我們。 – 2010-08-11 19:17:04

+0

不錯=) 感謝這兩個! – Francisco 2010-08-11 19:29:03

2

一個選項:創建一個包含CompletedReopen的接口,使類實現接口(通過部分類的手動位),然後編寫一個擴展該接口的擴展方法。我認爲應該工作:

public interface IPoll 
{ 
    bool Completed {get; set;} 
    bool? Reopen { get; set; } 
} 

// Actual implementations are in the generated classes; 
// no need to provide any actual code. We're just telling the compiler 
// that we happen to have noticed the two classes implement the interface 
public partial class DirectorPoll : IPoll {} 
public partial class StudentPoll : IPoll {} 

// Any common behaviour can go in here. 
public static class PollExtensions 
{ 
    public static bool CanEdit(this IPoll poll) 
    { 
     return !poll.Completed || poll.Reopen.GetValueOrDefault(false); 
    } 
} 

誠然那麼它必須是一個方法,而不是屬性,有沒有這樣的事,作爲一個擴展屬性,但是這不是一個太大的困難。

(我相信我在CanEdit你的邏輯重構是正確的所有這些顯性trues和falses在做着我的頭。)

+0

笑;我喜歡我們兩個人如何對付這個糟糕的'迴歸'; p你的'!'是錯位的,順便說一句。 – 2010-08-11 19:17:14

+0

@Marc:Doh--那是因爲忘記第一次包括'poll' :) – 2010-08-11 19:18:39

+0

我也注意到了;我太忙了簡化評論; p – 2010-08-11 19:19:30