【发布时间】:2013-08-23 23:38:15
【问题描述】:
我希望我的几个类能够告诉我其中有多少字段,并且我想通过继承强制我的所有类都具有此功能,如下所示:
// 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
}
}
}
有没有办法做到这一点,或者反射是唯一的方法吗?
谢谢!
【问题讨论】:
-
当然,反思是最好的选择——否则即使有办法使语法正常工作,还有什么能阻止您报告错误的数字?
-
您不能对静态成员使用多态性。您只能将
override用于方法、事件和属性。不是Fields或Constants -
@James 即使 Op 也更改为 Property 这也不起作用。因为成员是静态的
-
@SriramSakthivel 是的,注意到除了编译问题之外还有更多问题!
-
static和“继承”不能一起使用。事实上,static和 OO 不能一起工作。 (不在 C++/Java/C# 模型中。)
标签: c# generics inheritance