据我所知,这在 C# 中不起作用。您可以使用字段或在属性/方法中创建变量。在 VB.NET 中,您有Static
局部变量的关键字(见下文)。
您已经评论说您有许多派生类,并且您不希望每个派生类都有一个静态字段数组。我会建议使用不同的方法。您可以在基类中使用静态变量Dictionary
,并为每个派生类使用枚举:
abstract class Base
{
public abstract DerivedType Type { get; }
protected static readonly Dictionary<DerivedType, int[]> SomeDict;
static Base()
{
SomeDict = new Dictionary<DerivedType, int[]>();
SomeDict.Add(DerivedType.Type1, new int[] { 1, 2, 3, 4 });
SomeDict.Add(DerivedType.Type2, new int[] { 4, 3, 2, 1 });
SomeDict.Add(DerivedType.Type3, new int[] { 5, 6, 7 });
// ...
}
public static int[] SomeArray(DerivedType type)
{
return SomeDict[type];
}
}
public enum DerivedType
{
Type1, Type2, Type3, Type4, Type5
}
class Derived : Base
{
public override DerivedType Type
{
get { return DerivedType.Type1; }
}
}
但是,在 VB.NET 中,可以使用-keyword使用静态局部变量:Static
MustInherit Class Base
Public MustOverride ReadOnly Property someArray() As Integer()
End Class
Class Derived
Inherits Base
Public Overrides ReadOnly Property someArray() As Integer()
Get
Static _someArray As Int32() = New Integer() {1, 2, 3, 4}
Return _someArray
End Get
End Property
End Class
_someArray
对于 的每个实例都是相同的Derived
。