【问题标题】:Ways to automatically perform an operation on a class, and only do so once自动对类执行操作的方法,并且只执行一次
【发布时间】: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


【解决方案1】:

听起来你想要一个继承的静态初始化器,因为静态属性不是继承的,这不能直接工作。

但是,您可以选择向基类构造函数添加逻辑。添加一些逻辑来处理多种类型,并使用 this.GetType() 来获取当前类型。例如:

private static HashSet<Type> initializedTypes = new HashSet<Type>();
public BaseClass()
{
    if (!initializedTypes.Contains(this.GetType())
    {
        //Do something here
        initializedTypes.Add(this.GetType());
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-10
    • 2013-03-31
    • 1970-01-01
    • 1970-01-01
    • 2022-06-17
    相关资源
    最近更新 更多