2017-01-13 16 views
-2

オブジェクトにインターフェイスメソッドを使用する際に問題があります。私は、すべてのインプリメンテーションがなくても簡単な例を与えるつもりです。C#インターフェイスとクラスの継承

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を実装しているという事実を知っています。そしてその方法を持っている。それでもアクセスできませんか?

+4

どのようなプログラミング言語ですか?あなたの質問は 'c# 'とタグ付けされていますが、あなたの質問にあなたが示したことは、むしろ異なるものです。 –

+4

これがC#の場合、 'method'のエラーが表示されないことに驚いています。また、メソッド名の大文字と小文字を確認してください。 –

+0

私はあなたに保証します。私はちょうどそれがリターンを気にすることなく方法であることを示す方法を書いた。代わりにvoidと言ってふり返す – Mdsm

答えて

0

提供されている例の構文はC#のようには正確には見えませんが、あなたのものと似ている単純な例がここにあります。 ItemクラスにはExampleMethodはありませんが、AppleはインターフェイスIFruitを実装しているため、Appleが行います。ただし、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(); 

     } 
    } 
} 
+0

ありがとうございます。これは私が必要としたものです – Mdsm

5

まず、C#命名規則をお読みください。第二に、i_fruitインターフェイスを明示的に実装している場合、example_itemi_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(); 
+0

ちょうど私が編集した最新の質問に一致するようにあなたのコードを更新しました。 – Jamiec

+0

これは理にかなっているようです。しかし、暗黙のうちにそれを行うオプションは与えられていません。 – Mdsm

+0

@Jamiecありがとう! –

関連する問題