2017-01-27 44 views
-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. 

如何處理這種情況?我相信可能有一些設計模式可以解決這個問題,但我不習慣設計模式。任何建議都會非常有幫助。

+0

。 –

+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 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; 
} 

這也如果你想一個屬性是提供一個接口,將其添加到界面,然後進行重構,以

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

public string CreateResponseForB(B b) 
{ 
    return CreateResponse(b); 
} 
相關問題