【问题标题】:Purpose of interface variable in C# class implementationC#类实现中接口变量的用途
【发布时间】:2020-02-01 11:12:08
【问题描述】:

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

interface IThing
{
    string GetThing();
}

然后,当我生成样板时:

class ThingClass : IThing
{
    private IThing ThingImplementation;

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

那么,IThingThingImplementation 的实例是什么?

【问题讨论】:

  • 您可能选择了“通过委托给字段实现接口”操作。
  • 嗯,是的,既然你提到了它,我确实记得尝试过这个选项。

标签: c# roslyn rider


【解决方案1】:

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

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

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

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

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

当您想要“即时”更改实现时,第二个版本非常有用。可能取决于构造函数参数,或者您的用例。

【讨论】:

    猜你喜欢
    • 2019-04-16
    • 2016-06-03
    • 2017-12-24
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 2018-05-21
    • 1970-01-01
    相关资源
    最近更新 更多