Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/337.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 自动在类上执行操作且仅执行一次的方法_C#_.net_Inheritance_Attributes_Assemblies - Fatal编程技术网

C# 自动在类上执行操作且仅执行一次的方法

C# 自动在类上执行操作且仅执行一次的方法,c#,.net,inheritance,attributes,assemblies,C#,.net,Inheritance,Attributes,Assemblies,我试着做一些事情,从某个基类派生的所有类在加载时都会执行一些操作,但在程序执行期间只执行一次。我想让生成派生类的人不必做任何额外的工作。在我的示例中,我有OnInheritedAttribute(),这是我刚刚编写的,它在定义子类时调用输入的委托 public class DelegateHolder { public bool Operation(Type t) { /*...*/ }; static OnInheritedAttributeDelegate d = new O

我试着做一些事情,从某个基类派生的所有类在加载时都会执行一些操作,但在程序执行期间只执行一次。我想让生成派生类的人不必做任何额外的工作。在我的示例中,我有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;
     }
   }
}
但是如果要创建很多对象,这看起来很笨重,也很浪费


关于如何简化这个问题,有什么建议吗?

听起来您需要一个继承的静态初始值设定项,因为静态属性不是继承的,所以它不能直接工作

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

private static HashSet<Type> initializedTypes = new HashSet<Type>();
public BaseClass()
{
    if (!initializedTypes.Contains(this.GetType())
    {
        //Do something here
        initializedTypes.Add(this.GetType());
    }
}
private static HashSet initializedTypes=new HashSet();
公共基类()
{
如果(!initializedTypes.Contains)(this.GetType())
{
//在这里做点什么
initializedTypes.Add(this.GetType());
}
}

让我明白这一点-您希望类的每个实例都运行初始化代码吗?还是希望为每个加载的类型运行一次代码?无论哪种方式,您都在寻找构造函数或静态构造函数,对吗?@ananthonline:似乎他想要一个继承的静态初始值设定项。是的,我想要的是与继承的静态初始值设定项等效。我希望避免在每个初始化例程中都有额外的逻辑,以查看它是否已初始化。@sjamesstapleton:每个类都保证被CLR调用一次。如果您只查找一次,则
static ClassName(){}
应该可以正常工作,如果您正在寻找类之间的统一逻辑,请参阅我的答案。