簡體   English   中英

C#接口和類繼承

[英]C# interface and class inheritance

我在對象中使用接口方法時遇到問題。 我將舉一個沒有所有實現的簡單示例。

public class Item{}
public interface IFruit
{
      void MethodExample();
}

public class Apple : Item, IFruit
{
    public void IFruit.MethodExample(){}
}

// put this in a run method somewhere
var example_item = new Apple();

//Here comes the problem.
example_item.MethodExample();
// this will return an error saying that it cant find the method.

無論如何要做到這一點? 我知道它實現了 i_fruit 的事實。 並且有方法。 然而我無法訪問它?

首先,請閱讀 c# 命名約定。 其次,您已經顯式實現了i_fruit接口,您應該將example_item轉換為i_fruit或更常見的方法是隱式實現i_fruit接口。 請閱讀: https : //blogs.msdn.microsoft.com/mhop/2006/12/13/implicit-and-explicit-interface-implementations/

隱式實現示例:

public class Apple : Item, IFruit
{
   public MethodExample(){}
}

另一方面,如果您想堅持顯式實現,那么您應該將代碼更改為:

IFruit example_item;
example_item = new Apple();

您提供的示例中的語法並不完全像 C#,但這里有一個簡單的示例,它看起來與您的相似。 Item 類沒有 ExampleMethod,但 Apple 有,因為它實現了 IFruit 接口。 但是,您可以使用as關鍵字將對象臨時轉換為其他內容,從而訪問 ExampleMethod。 exampleFruit的示例中可以看到處理此類情況的常用方法。 希望這可以幫助。

using System;

namespace StackOverflowInterfaces
{
    class Item { }
    interface IFruit
    {
        void ExampleMethod();
    }

    class Apple : Item, IFruit
    {
        public void ExampleMethod()
        {
            throw new NotImplementedException();
        }
    }

    class MainClass
    {
        public static void Main()
        {
            Item exampleItem = new Apple();
            // exampleItem.ExampleMethod(); -- DOES NOT WORK, because Item does not implement IFruit
            (exampleItem as IFruit).ExampleMethod();
            (exampleItem as Apple).ExampleMethod();

            IFruit exampleFruit = new Apple();
            exampleFruit.ExampleMethod();

            Apple exampleApple = new Apple();
            exampleApple.ExampleMethod();

        }
    }
}

暫無
暫無

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

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