簡體   English   中英

如何調用在接口中定義並在C#中的類中實現的方法?

[英]How to call a method defined in interface and implemented in class in C#?

我有一個名為IAp.cs的接口文件,它實現了以下接口:

public interface IAp
{
    Output Process(double min, double max, IEnumerable<string> items);
}

然后,我有一個這樣定義的類:

[Export(typeof(IAp))]
public class Ap : IAp
{
    readonly ISorter _sorter;

    public Ap()
    {
        _sorter = ContainerProvider.Container.GetExportedValue<ISorter>();
    }

    Output IAp.Process(double min, double max, IEnumerable<string> items) 
    {
       // rest removed for brevity
    }
}

ISorter接口和ContainerProvider類的定義如下,但在單獨的文件中:

interface ISorter
{
    string Sort(string token);
}

internal static class ContainerProvider
{
    private static CompositionContainer container;

    public static CompositionContainer Container
    {
        get
        {
            if (container == null)
            {
                List<AssemblyCatalog> catalogList = new List<AssemblyCatalog>();
                catalogList.Add(new AssemblyCatalog(typeof(ISorter).Assembly));
                container = new CompositionContainer(new AggregateCatalog(catalogList));
            }

            return container;
        }
    }
}

現在,在另一個源文件中,我想調用Process方法。 我做了這樣的事情:

private readonly IAp _ap;
Output res = _ap.Process(50, 100, items);

但這表示_ap從未分配給它,並且它為null,因此它不調用Process方法。 它將引發NullReference錯誤。

我還嘗試如下初始化該類:

private Ap app = new Ap();

但是,如果我做app. 要訪問其成員,它找不到Process方法,它不存在。 有什么想法如何在另一個源文件和類中調用Process方法嗎?

您需要實例化該類,然后將其引用作為接口類型保存(因為Ap從接口IAp繼承,因此由於多態性而合法),例如:

private readonly IAp _ap =  new Ap();
Output res = _ap.Process(50, 100, items);
private IAp app = new Ap();

這是因為Ap實現了IAp 之所以不能做您想做的事情,是因為您使用的是顯式接口實現,所以接口方法僅在對接口的引用上可見,而在類上不可見。

有關顯式接口實現的詳細信息,請參見顯式接口實現教程

另一個解決方法是不使用顯式接口實現,但是這可能會使您直接引用類型,通常認為這不是最佳實踐。

代碼僅顯示更改的簽名實現。

public class Ap : IAp
{
    public Output Process(double min, double max, IEnumerable<string> items) 
    {
       // rest removed for brevity
    }
}

現在,使用您現有的參考也可以。

有關更多信息,請參閱《 接口-C#編程指南》

您看到的行為是因為接口已顯式實現。 您需要執行以下一項操作:

  1. App實例分配給IAp類型的變量:

     IAp _ap = new Ap(); //now you can do _app.Process 
  2. 隱式實現接口:

     public class Ap: IAp { public Output Process(....) { ... } } Ap _ap = new Ap(); //now you can do _ap.Process 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM