微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Singleton, Generic Singleton and Silverlight Reflection 限制

一个项目中,有一个类想实现为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 @R_296_4045@ion 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#) - 无法避免有人会直接调用该构造函数,只好加些注释了

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐