[英]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.