gpt4 book ai didi

c# - 在 C# 中使用接口(interface)作为 "out"参数

转载 作者:太空狗 更新时间:2023-10-29 23:09:18 26 4
gpt4 key购买 nike

如何在另一个接口(interface)的方法中使用一个接口(interface)或抽象类作为“out”参数?难道我不能将一个接口(interface)用作另一个接口(interface)中的输出参数,然后在我实际调用该方法时让它接受任何实现该接口(interface)的类吗?

我需要一个 Transaction 接口(interface),它有一个返回 bool 并填充“Response”对象的方法,但是对于 Transaction 接口(interface)的每个不同实现,该响应对象是一个不同的派生对象。提前致谢。

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

最佳答案

只要您适本地进行转换,您当前的实现就会工作:

public class TransactionDerived : ITransaction
{
public bool Validate(out IResponse theResponse)
{
theResponse = new ResponseDerived();
((ResponseDerived)theResponse).message = "My message";

return true;
}

public void Execute()
{
IResponse myResponse;

if (Validate(out myResponse))
Console.WriteLine(((ResponseDerived)myResponse).message);
}
}

然而,这很困惑。您可以通过使用通用接口(interface)来避免强制转换:

public interface ITransaction<T> where T : IResponse
{
bool Validate(out T theResponse);
}

public class TransactionDerived : ITransaction<ResponseDerived>
{
public bool Validate(out ResponseDerived theResponse)
{
theResponse = new ResponseDerived();
theResponse.message = "My message";

return true;
}

public void Execute()
{
ResponseDerived myResponse;

if (Validate(out myResponse))
Console.WriteLine(myResponse.message);
}
}

关于c# - 在 C# 中使用接口(interface)作为 "out"参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12553214/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com