2017-01-27 2 views
-2

更新:私の最初の計画は、アップキャストとダウンキャストにそれを使用することでした。私は、メソッドがサーバーからの異なる応答に基づいて異なるクラスを返すことができるようにしたいと思っています。Interfaceを使ってそれを実装したクラスにアクセスするには?

私はインターフェイスの高度な使い方を理解しようとしています。

public interface IMyInterface 
{ 

} 

私は以下のように上記のインターフェイスを実装する2つのクラスを持っています。

public class A:IMyInterface 
{ 
    public string AName { get; set; } 
} 

public class B : IMyInterface 
{ 
    public string BName { get; set; } 
} 

は今、私は以下のような4つの方法している:最後に、私はこのようなメソッドを呼び出すために

public IMyInterface CreateRawResponse() 
{ 
    if (condition) 
    { 
     return new A 
     { 
      AName = "A" 
     }; 
    } 
    else 
    { 
     return new B 
     { 
      BName = "B" 
     }; 
    } 
} 

public string CreateResponse(IMyInterface myInterface) 
{ 
    return myInterface. // I would like to access the properties of the  parameter, since its actually a class 
} 
public string CreateResponseForA(A a) 
{ 
    return a.AName; 
} 

public string CreateResponseForB(B b) 
{ 
    return b.BName; 
} 

をしようとしている:

var obj = new Program(); 
var KnownResponse = obj.CreateRawResponse(); // Lets say I know I will get type A 
var test1 = obj.CreateResponseForA(KnownResponse); //But I can't call like this, because CreateResponseForA() is expecting IMyInterface as parameter type. 
var UknownResponse = obj.CreateRawResponse(); // Lets say I don't know the response type, all I know is it implemented IMyInterface 

var test2 = obj.CreateResponse(UknownResponse); // I can call the method but can access the properties of the calling type in CreateResponse() mehtod. 

この種の状況を処理するためにどのように?私はこれを解決するためのデザインパターンがあると信じていますが、私はパターンをデザインするのに慣れていません。どんな助言も本当に役に立ちます。

+0

にリファクタリングすることができ

public IMyInterface CreateRawResponse() { if (condition) { return new A { Name = "A" }; } else { return new B { Name = "B" }; } } public string CreateResponse(IMyInterface myInterface) { return myInterface.Name; } public string CreateResponseForA(A a) { return a.Name; } public string CreateResponseForB(B b) { return b.Name; } 

。 –

+0

インターフェイスに共通のプロパティを持たせます。 'interface IMyInterface {string Name {get; }} ' – Nkosi

+0

あなたのインターフェイスは空です。必要な方法で使用するためには、それを実装するクラスに共通のアクセス可能なプロパティが必要です。それ以外の場合は、インターフェイスは非常に単純です。 –

答えて

2

インターフェイスはすべてのこと、あなたの状況になることを意味し、それを実装

public interface IMyInterface { 
    string Name { get; set; } 
} 

したがって

public class A:IMyInterface 
{ 
    public string Name { get; set; } 
} 

public class B : IMyInterface 
{ 
    public string Name { get; set; } 
} 

に共通のメンバーを持っている必要があります。あなたはプロパティは、インターフェースで利用できるようにそのインターフェイスに追加したい場合も、その後

public string CreateResponse(IMyInterface myInterface) 
{ 
    return myInterface.Name; 
} 
public string CreateResponseForA(A a) 
{ 
    return CreateResponse(a); 
} 

public string CreateResponseForB(B b) 
{ 
    return CreateResponse(b); 
} 
関連する問題