【发布时间】:2012-03-30 05:16:06
【问题描述】:
我正在尝试做一些事情,从某个基类派生的所有类在加载时都会执行一些操作,但在程序执行期间只执行一次。我想这样做,这样制作派生类的人就不必做任何额外的工作。在我的示例中,我有 OnInheritedAttribute(),它是我刚刚编写的,它会在定义子类时调用输入的委托。
public class DelegateHolder
{
public bool Operation(Type t) { /*...*/ };
static OnInheritedAttributeDelegate d = new OnInheritedAttributeDelegate(Operation);
}
[OnInheritedAttribute(DelegateHolder.d)]
public abstract class AInheritable
{ /*...*/ }
//ideally, I could do this, and have the processing done
public class SubClassA : AInheritable
{ /*...*/ }
//which would have the same effect as this, no attribute were assigned to AInheritable
public class SubClassB : AInheritable
{
private static readonly bool _dummy = DelegateHolder.Operation(SubClassB);
}
我几乎肯定第二种方法会做我想做的事(前提是程序集没有被多次加载),但是让 AInheritable 的每个子类都需要调用此代码似乎真的很烦人。
另一个选项可能是
public class BaseClass
{
static bool initialized; //this may not work, it will probably make one value for all classes rather than each subclass.
public BaseClass()
{
if(!/*System.Reflection code to get static member initialized from class of (this)*/)
{
/*perform registration*/
/*System.Reflection code to get static member initialized from class of (this)*/ = true;
}
}
}
但是如果要创建很多对象,这似乎很笨重,而且很浪费。
有什么关于简化这个的建议吗?
【问题讨论】:
-
让我明白这一点——你想让一个类的每个实例都运行初始化代码吗?或者您是否希望某些代码为每个加载的类型运行一次?无论哪种方式,您都在寻找构造函数或静态构造函数,对吗?
-
@ananthonline:看起来他想要一个继承的静态初始化器。
-
是的,我想要的是相当于继承的静态初始化程序。我想避免在每个初始化例程中都有额外的逻辑来查看它是否已经初始化。
-
@SJamesSstapleton: Static constructors 保证每个类被 CLR 调用一次。如果您正在寻找一次性的东西,那么
static ClassName() {}应该可以正常工作,如果您正在寻找类之间的统一逻辑,请参阅我的答案。
标签: c# .net inheritance attributes assemblies