一个项目中,有一个类想实现为Singleton,查阅了下发现 .NET CLR 已经可以确保诸如线程安全之类的问题,实现一个.NET Singleton很简单:
sealed class Singleton
{
private Singleton() {}
public static readonly Singleton Instance = new Singleton();
}
但是项目中有一些列的类需要实现为Singleton,就需要一个支持泛型的Singleton, 有人已经给出了一个实现:该实现方法基于Reflection 创建Singleton 实例,这是因为需要实现为Singleton的类应该不能有public 构造函数,否则程序员可直接调用该构造函数,Singleton无从体现了。
似乎可以借鉴来用了!项目是Silverlight项目,拿来应用编译成功。可是,运行时却出错,得到System.MethodAccessException。
Silverlight 的 compacted .net Framework 还是有些限制, 不同于 full .net framework:
Reflection provides the ability to obtain information about types and members, and to access members. In Silverlight, you can use reflection to perform the following tasks:
Enumerate types and members, and examine their metadata.
Enumerate and examine assemblies and modules.
Access public members.
Access internal members (Friend members in Visual Basic) in the calling code's assembly. (In reflection, this is referred to as assembly-level access.)
In Silverlight, you cannot use reflection to access private types and members. If the access level of a type or member would prevent you from accessing it in statically compiled code, you cannot access it dynamically by using reflection.
这样一来,只好把需要实现为singleton 类的构造函数修饰为 internal (C#) - 无法避免有人会直接调用该构造函数,只好加些注释了