2013-08-16 33 views
0

我想讓我的幾個課程能夠告訴我它們中有多少個字段,並且我想強制所有的類都通過繼承來實現,如下所示:一個類中的靜態信息

// this code does not compile 
abstract class Base 
{ 
    abstract static const int FieldCount = -1 
} 

class Node : Base 
{ 
    int x, y, z; // has three fields, so: 
    override static const int FieldCount = 3; 
} 

class Way : Base 
{ 
    int w, x, y, z; // has four fields, so: 
    override static const int FieldCount = 4; 
} 

我不能讓它工作,而不是一個接口或抽象基類。我需要這些信息與類型一起使用,而不是通過類的實際實例(因此是靜態的)。

class EnumerableDataReader<TSource> : IDataReader where TSource : Base { 
    public int FieldCount { 
     get { 
      return TSource.FieldCount <- access the static info, does not work 
     } 
    } 
} 

有沒有辦法做到這一點,或將在這裏反思是唯一的出路?

謝謝!

+1

當然反思的是要走的路 - 否則你會從報告了錯誤的號碼,即使有一個方法,使語法工作阻止你? – Jon

+0

你不能爲靜態成員使用多態。您只能將'override'僅用於方法,事件和屬性。不用'Fields'或'Constants' –

+0

@James即使當操作改變屬性也是行不通的。因爲成員是**靜態** –

回答

0

看起來不像有任何真正需要具體在這裏使用的字段,如果您切換到使用屬性,而不是你可以重寫即

abstract class Base 
{ 
    public static int FieldCount { get { return -1; } } 
} 

class Node : Base 
{ 
    int x, y, z; // has three fields, so: 
    public new static int FieldCount { get { return 3; } } 
} 

class Way : Base 
{ 
    int w, x, y, z; // has four fields, so: 
    public new static int FieldCount { get { return 4; } } 
} 
... 
Console.WriteLine(Base.FieldCount) // -1 
Console.WriteLine(Node.FieldCount) // 3 
Console.WriteLine(Way.FieldCount) // 4 

在各導出的屬性實現解決的另一半您的問題,您將需要依靠反射即

class EnumerableDataReader<TSource> where TSource : Base 
{ 
    public int FieldCount 
    { 
     get { 
      return (int)typeof(TSource).GetProperties().Single(x => x.Name == "FieldCount").GetValue(null); 
     } 
    } 
} 
... 
var reader = new EnumerableDataReader<Node>(); 
Console.WriteLine(reader.FieldCount); // 3 
0

靜態成員不支持虛擬繼承,因爲虛擬繼承是關於解析給定的實例成員。實例中不存在靜態成員。

您可以使用反射來讀取給定類型參數或Type實例的靜態成員。

在你的設計中有很多「魔力」。一位新開發人員可能不會立即採用具有特殊名稱字段的慣例。我會考慮將您的TSource類型的設計更改爲自定義屬性

0

您可以使用單獨的靜態類來存儲字段計數或任何類型特定的數據。靜態類中的靜態字段每個類型都是唯一的,這意味着MyStaticClass.FieldCount是與MyStaticClass.FieldCount不同的變量。

此外,您可以使用靜態構造函數來設置該類觸摸的第一個類型的值。

例如,

public static class FieldCountStatic<T> 
{ 
    public static int FieldCount { get; set; } 
} 

class Node 
{ 
    static Node() 
    { 
     FieldCountStatic<Node>.FieldCount = 3; 
    } 

    int x, y, z; 
} 

class Way 
{ 
    static Way() 
    { 
     FieldCountStatic<Way>.FieldCount = 4; 
    } 

    int w, x, y, z; // has four fields 

} 

class EnumerableDataReader<TSource> : IDataReader 
{ 
    public int FieldCount 
    { 
     get 
     { 
      return FieldCountStatic<TSource>.FieldCount; 
     } 
    } 
}