如何在另一個接口的方法中使用接口或抽象類作爲「out」參數?我不應該能夠在另一個接口中使用接口作爲out參數,然後讓它在我實際調用方法時接受實現該接口的任何類?在C#中使用接口作爲「out」參數
我需要一個Transaction接口,它有一個方法返回一個bool並填充一個「Response」對象,但該響應對象是Transaction接口的每個不同實現的不同派生對象。提前致謝。
namespace csharpsandbox
{
class Program
{
static void Main(string[] args)
{
TransactionDerived t = new TransactionDerived();
t.Execute();
}
}
public interface ITransaction
{
bool Validate(out IResponse theResponse);
}
public interface IResponse { }
public class ResponseDerived : IResponse
{
public string message { get; set; }
}
public class TransactionDerived : ITransaction
{
public bool Validate(out IResponse theResponse) {
theResponse = new ResponseDerived();
theResponse.message = "My message";
return true;
}
public void Execute()
{
ResponseDerived myResponse = new ResponseDerived();
if (Validate(out myResponse))
Console.WriteLine(myResponse.message);
}
}
}
這看起來像一個很好的解決方案,將測試並確保它能夠滿足我短期所需,謝謝! – ARW
我剛剛意識到這不會起作用,因爲每個事務實現實際上可以有多個唯一的響應...我最好打賭然後投射嗎? – ARW
沒有看到系統的其他部分,鑄造(使用'as'操作符可能會更清潔一些)聽起來是最容易做的事情。但要小心,如果你發現自己需要檢查類型並投入很多東西,它通常會在設計中指出一個更大的問題。 – verdesmarald