-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.
この種の状況を処理するためにどのように?私はこれを解決するためのデザインパターンがあると信じていますが、私はパターンをデザインするのに慣れていません。どんな助言も本当に役に立ちます。
にリファクタリングすることができ
。 –
インターフェイスに共通のプロパティを持たせます。 'interface IMyInterface {string Name {get; }} ' – Nkosi
あなたのインターフェイスは空です。必要な方法で使用するためには、それを実装するクラスに共通のアクセス可能なプロパティが必要です。それ以外の場合は、インターフェイスは非常に単純です。 –