Singleton, Generic Singleton and Silverlight Reflection 限制

110 篇文章 0 订阅
90 篇文章 0 订阅

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

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值