-2
更新:我最初的計劃是將它用於上傳和向下轉換。我只是希望我的方法能夠根據服務器的不同響應返回不同的類。如何使用接口訪問實現它的類?
我想了解高級界面的使用。可以說我有一個跨臉像波紋管:
public interface IMyInterface
{
}
我有兩個類實現像波紋管上面的接口。
public class A:IMyInterface
{
public string AName { get; set; }
}
public class B : IMyInterface
{
public string BName { get; set; }
}
現在我有一個像下面四種方法:
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
你的界面是空的。它需要有一個可訪問的屬性,這對於實現它的類來說是通用的,以便以你想要的方式使用它。否則,你的界面簡直毫無意義。 –