Leo*_*Hat 5 .net c# reflection static
我编写了以下控制台应用程序来测试静态属性:
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
}
}
}
Run Code Online (Sandbox Code Playgroud)
正如此控制台应用程序演示的那样,该MyProperty属性对于BaseClass的所有实例都存在一次.是否有一种模式可以让我定义一个静态属性,它将为每个子类类型分配存储空间?
鉴于上面的示例,我希望所有实例DerivedAlpha共享相同的静态属性,并且所有实例DerivedBeta共享另一个静态属性实例.
我为什么要这样做?
我懒洋洋地初始化具有某些属性的类属性名称集合(通过反射).每个派生类实例的属性名称都是相同的,因此将它存储在每个类实例中似乎很浪费.我不能在基类中使它静态,因为不同的子类将具有不同的属性.
我不想复制在每个派生类中填充集合(通过反射)的代码.我知道一种可能的解决方案是定义在基类中填充集合的方法,并从每个派生类中调用它,但这不是最优雅的解决方案.
更新 - 我正在做的事情的例子
在Jon的要求下,这是我正在尝试做的一个例子.基本上,我可以选择用属性装饰我的类中的[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; }
}
Run Code Online (Sandbox Code Playgroud)
期望的最终结果
访问FooEntity.PropertiesWithDoNotInclude返回a List<string>:
{
"Property_A",
"Property_C"
}
Run Code Online (Sandbox Code Playgroud)
访问BarEntity.PropertiesWithDoNotInclude返回a List<string>:
{
"Property_E"
}
Run Code Online (Sandbox Code Playgroud)
乔恩像往常一样有一个很好的解决方案,尽管我看不出属性在这里有什么作用,因为它们必须显式添加到每个子类型中,并且它们的行为不像属性。
这个Dictionary方法绝对有效。这是另一种方法,它显式声明 的每个子类将有一个变量BaseEntity:
class FilteredProperties<T> where T : BaseEntity
{
static public List<string> Values { get; private set; }
// or static public readonly List<string> Values = new List<string>();
static FilteredProperties()
{
// logic to populate the list goes here
}
}
Run Code Online (Sandbox Code Playgroud)
这样做的缺点是,GetType()与您可能在 的方法中使用的调用配对相当困难BaseEntity。ADictionary或实现惰性填充的包装器更适合这种用法。