看,我知道靜態類不能繼承或實現。問題是「什麼是是正確的C#+ OOP模式來實現這個?」。 「This」描述如下:如何在靜態類中使用多態或繼承?
我想爲一組類定義和實現的通用集合,其中除一個類型之外的所有類型都應該是靜態的。也就是說,我要做出一些武斷基地轉換器,其中每個具有完全相同的四個成員:
// Theoritical; static classes can't actually implement
interface IBaseConverter {
int Base { get; }
char[] Glyphs { get; }
int ToInt(string value);
string FromInt(int value);
}
// AND/OR (interface may be superfluous)
public class BaseConverter : IBaseConverter{
public BaseConverter(int Base, char[] Glyphs) {
this.Base = Base;
this.Glyphs = Glyphs;
}
public int Base { get; private set; }
public char[] Glyphs { get; private set;}
public int ToInt(string value) { // shared logic...
public string FromInt(int value) { // shared logic...
}
他們還可以共享基礎上的Base
價值和字形的有序集合完全相同的實現邏輯。例如Base16Converter
可能有Base = 16
和glyphs = { '0', '1', ... 'E', 'F' }
。我相信FromInt
和ToInt
是不言自明的。顯然,我不需要實現基於16的轉換器,但是我需要爲特定於行業的基礎36(0
- Z
Code 39的字形)實現一個轉換器。與內置的轉換和字符串格式化功能(如[Convert]::ToInt32("123",16)
)一樣,這些都是強調靜態方法 - ,當基礎和字形預先確定時。
我想保持可與任意的字形和底座,如被初始化實例的版本:
BaseConverter converter = new BaseConverter(7, new[]{ 'P', '!', 'U', '~', 'á', '9', ',' })
int anumber = converter.ToInt("~~!,U") // Equals 8325
但我也希望有一個靜態類的Base36Code39Converter
。把這個的另一種方式是,任何static
實施者只是硬編碼的基礎和字形:
// Theoritical; static classes can't inherit
public static class Base36Code39Converter : BaseConverter {
private static char[] _glyphs = { '0', '1', ... 'Z' };
static Base36Code39Converter : base(36, _glyphs) { }
}
我明白爲什麼這不會對編譯器的工作 - 沒有虛函數表的靜態方法和所有。我知道在C#中,靜態類不能實現接口或從任何東西(除了對象)繼承(請參見Why Doesn't C# Allow Static Methods to Implement an Interface?,Why can't I inherit static classes?)。
那麼到底什麼是是的「右」C#+ OOP模式來實現這個?
這不是[單件模式](http://www.dofactory.com/Patterns/PatternSingleton.aspx)的工作嗎?另外,這裏有一篇關於[Singleton VS Static Class](http://www.dotnetperls.com/singleton-static)的好文章。 – 2012-02-15 14:46:36