繁体   English   中英

C#类实现中接口变量的用途

[英]Purpose of interface variable in C# class implementation

所以,开始熟悉 Rider IDE。 我定义了一个接口,然后设置了一个类来实现这个接口。 当我使用 Roslyn fix 来实现接口成员时,它产生了一些我以前没有注意到的东西,我想知道它的目的是什么。

interface IThing
{
    string GetThing();
}

然后,当我生成样板时:

class ThingClass : IThing
{
    private IThing ThingImplementation;

    public string GetThing()
    {
        throw new NotImplementedException();
    }
}

那么, IThing ThingImplementation的实例是IThing ThingImplementation用的呢?

Rider 提供了两个用于实现接口的快速修复程序。

骑士快速修复

第一个“实现缺失的成员”产生以下(预期的)代码:

class ThingClass : IThing
{
    public string GetThing()
    {
        throw new System.NotImplementedException();
    }
}

第二个“将 'IThing' 的实现委托给新字段”产生原始问题中的代码:

class ThingClass : IThing
{
    private IThing thingImplementation;
    public string GetThing()
    {
        return thingImplementation.GetThing();
    }
}

当您想“即时”更改实现时,第二个版本很有用。 也许取决于构造函数参数,或者无论您的用例是什么。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM