我编写了以下控制台应用程序来测试静态属性:
using System;
namespace StaticPropertyTest
{
public abstract class BaseClass
{
public static int MyProperty { get; set; }
}
public class DerivedAlpha : BaseClass
{
}
public class DerivedBeta : BaseClass
{
}
class Program
{
static void Main(string[] args)
{
DerivedBeta.MyProperty = 7;
Console.WriteLine(DerivedAlpha.MyProperty); // outputs 7
}
}
}
正如此控制台应用程序所示,MyProperty
属性对于 BaseClass 的所有实例都存在一次。是否有一种模式可以让我定义一个静态属性,该属性将为每个子类类型分配存储空间?
鉴于上面的例子,我想要的所有实例DerivedAlpha
共享相同的静态属性,并且所有实例DerivedBeta
分享another静态属性的实例。
我为什么要尝试这样做?
我正在惰性地初始化具有某些属性的类属性名称的集合(通过反射)。每个派生类实例的属性名称都是相同的,因此将其存储在每个类实例中似乎很浪费。我无法在基类中将其设为静态,因为不同的子类将具有不同的属性。
我不想在每个派生类中复制填充集合(通过反射)的代码。我知道一种可能的解决方案是在基类中定义填充集合的方法,并从每个派生类中调用它,但这不是最优雅的解决方案。
更新 - 我正在做的事情的例子
应乔恩的要求,这是我正在尝试做的一个示例。基本上,我可以选择用以下方式装饰我的类中的属性[SalesRelationship(SalesRelationshipRule.DoNotInclude)]
属性(还有其他属性,这只是一个简化的例子)。
public class BaseEntity
{
// I want this property to be static but exist once per derived class.
public List<string> PropertiesWithDoNotInclude { get; set; }
public BaseEntity()
{
// Code here will populate PropertiesWithDoNotInclude with
// all properties in class marked with
// SalesRelationshipRule.DoNotInclude.
//
// I want this code to populate this property to run once per
// derived class type, and be stored statically but per class type.
}
}
public class FooEntity : BaseEntity
{
[SalesRelationship(SalesRelationshipRule.DoNotInclude)]
public int? Property_A { get; set; }
public int? Property_B { get; set; }
[SalesRelationship(SalesRelationshipRule.DoNotInclude)]
public int? Property_C { get; set; }
}
public class BarEntity : BaseEntity
{
public int? Property_D { get; set; }
[SalesRelationship(SalesRelationshipRule.DoNotInclude)]
public int? Property_E { get; set; }
public int? Property_F { get; set; }
}
期望的最终结果
访问FooEntity.PropertiesWithDoNotInclude
返回一个List<string>
of:
{
"Property_A",
"Property_C"
}
访问BarEntity.PropertiesWithDoNotInclude
返回一个List<string>
of:
{
"Property_E"
}