私人只读接口 - 它是多余的? [英] Private readonly Interface - is it redundant?

查看:280
本文介绍了私人只读接口 - 它是多余的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的IoC和DI为我的项目。

I am using IoC and DI for my project.

不过,我想知道,如果它是很好的做法有以下几种:

However I was wondering if it is good practise to have the following:

private readonly IMyService myservice;

,因为这是消费者的服务的类内部的磁场。该字段设置在构造函数中。

as the field inside the class that is a consumer of the service. The field is set in the constructor.

我敢肯定,我已经看到了这个地方,我拿起它。 不过,我也看到了:

I'm sure I've seen this somewhere and I've picked up on it. However I also see:

private IMyService myservice;

和它似乎足够了。有什么目的,有一个只读字段注入的服务接口?有什么优势?

and it seems to suffice. Is there any purpose to have a readonly field for the injected service interface? What are the advantages?

推荐答案

我认为使用只读关键词的正确实施构造器注入的核心部分。

I consider use of the readonly keyword a central part of proper implementation of Constructor Injection.

public class MyClass
{
    private readonly IMyService myservice;

    public MyClass(IMyService myservice)
    {
        if (myservice == null)
        {
            throw new ArgumentNullException("myservice");
        }
        this.myservice = myservice;
    }
}

无论是只读关键字,也没有保护条款在技术上的需要的实施构造器注入。但是,它们都有助于加强类的不变量。 这就是封装是所有关于

Neither the readonly keyword nor the Guard Clause are technically required to implement Constructor Injection. However, they both help strengthen the invariants of the class. This is what encapsulation is all about.

这篇关于私人只读接口 - 它是多余的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆