在C#中使用接口作为“out”参数

时间:2012-09-23 14:38:04

标签: c# interface polymorphism abstract-class

如何在另一个接口的方法中将接口或抽象类用作“out”参数?我不应该在另一个接口中使用接口作为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);
    }
}
}

2 个答案:

答案 0 :(得分: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);
    }
}

答案 1 :(得分:1)

空接口定义毫无意义(参见here)。相反,尝试这样的事情:

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

然后适当地投射你的物体。