5

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

我需要一个事务接口,它有一个返回布尔值并填充“响应”对象的方法,但该响应对象是事务接口的每个不同实现的不同派生对象。提前致谢。

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

2 回答 2

5

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

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

然而,这很混乱。您可以通过使用通用接口来避免强制转换:

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);
    }
}
于 2012-09-23T14:47:14.623 回答
1

空的接口定义是没有意义的(见这里)。相反,尝试这样的事情:

public interface ITransaction
{
    bool Validate(out object theResponse);
} 

然后适当地投射你的对象。

于 2012-09-23T14:43:23.077 回答