我需要运行一些代码来为工厂模式注册一个类型。我会在 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/