C# 在密封类中实例化另一个类
在密封类中实例化另一个类的推荐方法是:C# 在密封类中实例化另一个类,c#,.net,C#,.net,在密封类中实例化另一个类的推荐方法是: public sealed class AvayaService { private static Lazy<AvayaService> lazy = new Lazy<AvayaService>(() => new AvayaService()); public static AvayaService AvayaServiceInstance { get
public sealed class AvayaService
{
private static Lazy<AvayaService> lazy =
new Lazy<AvayaService>(() => new AvayaService());
public static AvayaService AvayaServiceInstance
{
get
{
if (!lazy.IsValueCreated)
lazy = new Lazy<AvayaService>(() => new AvayaService());
return lazy.Value;
}
}
private AvayaService()
{
}
public static Response GetResponse(Request request)
{
var _repository = new Repository(); // what is the best way to get the instance here
}
}
public class Repository : IRepository
{
...
}
公共密封类AvayService
{
私有静态懒惰=
新的懒惰(()=>新的AvayService());
公共静态AvayService AvayService实例
{
得到
{
如果(!lazy.IsValueCreated)
懒惰=新懒惰(()=>新AvayService());
返回lazy.Value;
}
}
私有AvayService()
{
}
公共静态响应GetResponse(请求)
{
var _repository=new repository();//在这里获取实例的最佳方法是什么
}
}
公共类存储库:IRepository
{
...
}
我试图学习密封类和惰性实例化,但我正在思考在密封类中实例化另一个类的推荐方法是什么?在这方面没有“推荐”。如果你读过推荐信,请再读一遍,很可能这只是一个练习。它给了你一个想法,但在实际项目中使用这个想法取决于你。有时,这些练习展示了相反的方法。有时,存储库所有者会指定与您以前阅读过的任何规则相违背的样式,这是完全正确的
这里有另一个实例化练习,我认为这对尝试很有帮助:除了值对象之外,永远不要实例化任何东西。将实例化委托给。避免单例模式,但在容器中将服务注册为单例。这样,您的代码将如下所示:
public sealed class AvayaService
{
private readonly IRepository _repository;
public AvayaService(IRepository repository)
{
if(repository == null)
throw new ArgumentNullException();
_repository = repository;
}
public static Response GetResponse(Request request)
{
// use _repository
}
}
sealed
表示您不能从中继承。我不确定sealed
与您的代码有什么关系您正在用side静态函数实例化内容。正如@CamiloTerevinto所述,这与sealed关键字无关。实例化新类的方法是使用new
关键字。无论代码在何处运行,这都是正确的:在密封的类中,在未密封的类中,在静态方法中,在任何内部。唯一一次不使用new
关键字是在使用反射时。静态函数可以在任何地方调用。-与成员函数不同,成员函数必须在实例化的object@JohnWu或者在使用依赖项注入时。。。