【发布时间】:2010-12-21 04:46:07
【问题描述】:
我需要运行一些代码来为工厂模式注册一个类型。我会在 Java 中使用静态初始化块或在 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)
{
}
}
}
什么都没有打印出来。
【问题讨论】:
标签: c# static initialization