我想讓我的幾個課程能夠告訴我它們中有多少個字段,並且我想強制所有的類都通過繼承來實現,如下所示:一個類中的靜態信息
// 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
}
}
}
有沒有辦法做到這一點,或將在這裏反思是唯一的出路?
謝謝!
當然反思的是要走的路 - 否則你會從報告了錯誤的號碼,即使有一個方法,使語法工作阻止你? – Jon
你不能爲靜態成員使用多態。您只能將'override'僅用於方法,事件和屬性。不用'Fields'或'Constants' –
@James即使當操作改變屬性也是行不通的。因爲成員是**靜態** –