c# - C# 中的非惰性静态初始化 block

标签 c# static initialization

我需要运行一些代码来为工厂模式注册一个类型。我会在 Java 中使用静态初始化 block 或在 C++ 中使用静态构造函数来执行此操作。

如何在 C# 中执行此操作?该静态构造函数延迟运行,并且由于代码中永远不会引用该类型,因此永远不会注册。

编辑:我尝试了一个测试来查看注册码是否有效。但这似乎不起作用。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

[assembly: AssemblyTest.RegisterToFactory("hello, world!")]

namespace AssemblyTest
{
    [AttributeUsage(AttributeTargets.Assembly, Inherited = false, AllowMultiple = true)]
    sealed class RegisterToFactoryAttribute : Attribute
    {
        public RegisterToFactoryAttribute(string name)
        {
            Console.WriteLine("Registered {0}", name);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
        }
    }
}

什么都不打印。

最佳答案

程序集级属性的构造函数中怎么样?

示例:

[AttributeUsage(AttributeTargets.Assembly, Inherited = false, AllowMultiple = true)]
sealed class RegisterToFactoryAttribute : Attribute
{
    public Type TypeToRegister { get; set; }

    public RegisterToFactoryAttribute(Type typeToRegister)
    {
        TypeToRegister = typeToRegister;

        // Registration code
    }
}

用法:

[assembly:RegisterToFactory(typeof(MyClass))]

--编辑汇编级属性--

经过一些研究,我认为它只会在查询时加载程序集属性:

示例:

object[] attributes =
    Assembly.GetExecutingAssembly().GetCustomAttributes(
        typeof(RegisterToFactoryAttribute), false);

object[] attributes =
    Assembly.GetExecutingAssembly().GetCustomAttributes(false);

不知道为什么,但是将这段代码放在@程序加载中应该可以做到。

--编辑--

我差点忘了:

您是否考虑过使用 MEF ??这是解决这个问题的好方法。

示例:

class MyFactory
{
    [ImportMany("MyFactoryExport")]
    public List<Object> Registrations { get; set; }

    public MyFactory()
    {
        AssemblyCatalog catalog = new AssemblyCatalog(System.Reflection.Assembly.GetExecutingAssembly());
        CompositionContainer container = new CompositionContainer(catalog);
        container.ComposeParts(this);
    }
}

[Export("MyFactoryExport")]
class MyClass1
{ }

[Export("MyFactoryExport")]
class MyClass2
{ }

[Export("MyFactoryExport")]
class MyClass3
{ }

关于c# - C# 中的非惰性静态初始化 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4496362/

相关文章:

ios - 每当调用 View Controller 时,保存在 NSUserDefaults 中的 NSArray 的内容都会被覆盖

swift - 你能利用 Swift 的结构默认初始化器来简化参数传递吗?

c++ - 仅重新初始化派生类中的所有成员变量

c# - 在 C# 中模拟非虚拟方法

c# - 用单声道编译cs文件?

java - Spring 静态方法

php - 非静态方法......不应该被静态调用

c# - 应该如何实现 DbContext 和与 DB 的连接来处理负载测试?

c# - WPF组合框怪异问题

php - 如何在PHP中调用父类的非静态方法形成子类的静态方法