我有以下基础和派生(部分,为了简洁起见)类:
class Base {
public abstract int[] someArray { get; }
}
class Derived : Base {
private readonly static int[] _someArray = new int[] { 1,2,3,4 };
public override int[] someArray {
get {
return _someArray;
}
}
}
我现在想要的是将new int[] { 1,2,3,4 }
放在getter的return
部分。但是,每次调用getter时都会创建一个新数组。
是否可以直接返回某种对象,对于类Derived
的所有对象保持不变?
有些事情(我知道这是无效的C#):
get {
return (int[]) { 1, 2, 3, 4 };
}
答案 0 :(得分:4)
如果您只想将new int[] { 1,2,3,4 }
部分放入吸气器,那很容易......
private static int[] _someArray = null;
public override int[] someArray {
get {
return _someArray ?? (_someArray = new int[] { 1,2,3,4 });
}
}
然而,你失去了readonly。
更新:泛型解决方案
或者您可以滥用泛型的功能:
// Of course you still want to use the non-generic class Base
abstract class Base {
public abstract int[] someArray { get; }
}
abstract class Base<T> : Base where T: Base<T> {
// Will be created once for every T, i.e. every derived class.
private static int[] _someArray;
public override int[] someArray {
get { return _someArray ?? (_someArray = CreateArray()); }
}
protected abstract int[] CreateArray();
}
sealed class Derived : Base<Derived> {
protected sealed override int[] CreateArray() {
return new int[] { 1,2,3,4 };
}
}
sealed class DerivedB : Base<DerivedB> {
protected sealed override int[] CreateArray() {
return new int[] { 2,3,4,5 };
}
}
请注意,这只适用于一个继承级别,所以我密封了一些东西:)
答案 1 :(得分:0)
据我所知,在C#中不起作用。您可以使用字段或在属性/方法中创建变量。在VB.NET中,您有局部变量的Static
关键字(见下文)。
您已经评论过您有许多派生类,并且您不希望每个派生类都有一个静态字段数组。我建议使用不同的方法。你可以f.e.在基类中使用静态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中,可以使用static local variable使用Static
-keyword:
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
都是相同的。