Singleton, Generic Singleton and Silverlight Reflection 限制

Singleton, Generic Singleton and Silverlight Reflection 限制,第1张

概述一个项目中,有一个类想实现为Singleton,查阅了下发现 .NET CLR 已经可以确保诸如线程安全之类的问题,实现一个.NET Singleton很简单:   sealed class Singleton {     private Singleton() {}     public static readonly Singleton Instance = new Singleton(); @H_419_1@

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

总结

以上是内存溢出为你收集整理的Singleton, Generic Singleton and Silverlight Reflection 限制全部内容,希望文章能够帮你解决Singleton, Generic Singleton and Silverlight Reflection 限制所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/web/1050757.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-25
下一篇2022-05-25

发表评论

登录后才能评论

评论列表(0条)

    保存