从C#中基于输入参数类型的方法返回特定类型

时间:2014-03-20 08:39:51

标签: c# generics

我有4个输入类型说

  • T1:类AInput,类BInput,类CInput和类DInput

我还有3个输出类型说

  • T2:XOutput,类YOutput和类ErrorOutput

现在我必须在服务类中写一个通用的方法说“GetResponse”,如下所示 -

  1. 如果方法GetResponse的输入参数属于类 AInput 和类 BInput ,则此方法应返回类 XOutput < /强>

  2. 如果方法GetResponse的输入参数属于类 CInput 和类 DInput ,则此方法应返回类 YOutput < /强>

  3. 如果出现任何错误,此方法将返回类型类 ErrorOutput

  4. 现在我的问题是,具有通用方法的服务类是否可以遵循上述条件?

4 个答案:

答案 0 :(得分:0)

不,泛型类型约束在.NET中不具备此类高级概念。您可以改为提供重载:

XOutput Foo (AInput a);
XOutput Foo (BInput b);
YOutput Foo (CInput b);
YOutput Foo (DInput b);

答案 1 :(得分:0)

是的,您可以通过为所有输入和输出类实现interface来实现某种形式。像其他人提到的那样也可以用基类来完成,但是使用接口的imo更好,因为你不能继承多个类但是实现了多个接口。

输入类和接口:

interface IInput {}

class AInput : IInput {}

class BInput : IInput {}

class CInput : IInput {}

输出类和接口:

interface IOutput {}

class XOutput : IOutput {}

class YOutput : IOutput {}

class ErrorOutput : IOutput {}

方法:

public IOutput GetResponse(IInput input)
{
    if (input is AInput || input is BInput)
    {
        return new XOutput();
    }

    if (input is CInput || input is DInput)
    {
        return new YOutput();
    }

    return new ErrorOutput();
}

用法:

var input = new AInput();

var response = GetResponse(input);

if(response is XOutput)
{
    Console.WriteLine("Input was {0} and output was {1}", input.GetType().Name, response.GetType().Name);
} else if (response is YOutput)
{
    Console.WriteLine("Input was {0} and output was {1}", input.GetType().Name, response.GetType().Name);
}

输出:

"Input was Ainput and output was XOutput"

答案 2 :(得分:0)

假设我们在这里谈论WCF服务,你就不能拥有所谓的“开放”泛型。 Microsoft通过以下方式区分开放和封闭的泛型:

  • 开放式泛型是类似GetStuff<T>的方法,其中T可以由调用者指定,因此保持打开状态。
  • 封闭的泛型是类似GetStuff<int>的方法。该类型是立即知道的,WCF可以确定将为其WSDL传递的类型。

不支持formet,后者是。这意味着你必须经历一些麻烦才能使伪泛型工作在你的WCF服务上。

这样做的一种方法是为您通过操作返回的每种类型声明一个基类,例如您的案例中的OutputBase。然后,您可以通过继承基类来创建其他输出类型,并在Web服务中添加一些内容:

public OutputBase GetResponse(Type type, params object[] args)
{
    if (typeof(type) == typeof(AInput) || typeof(type) == typeof(BInput))
    {
        // Return object of type XOutput which inherits OutputBase here.
        var ret = new XOutput();
        return ret;
    }

    if (typeof(type) == typeof(CInput) || typeof(type) == typeof(DInput))
    {
        // Return stuff of type YOutput here.
        var ret = new YOutput();
        return ret;
    }

    return new ErrorOutput();
}

我不完全确定你是否可以在WCF服务调用中实际传递Type,但假设你不能将Type.FullName作为字符串传递并稍后使用{重新构建它{1}}将它投射到您所追求的那个。

希望有所帮助!

答案 3 :(得分:0)

如果您想使用Generics,则可以将GetResponse方法定义为

public XOutput GetResonse<TInput1, TInput2>(TInput1 input1, TInput2 input2, out ErrorOutput error)
    where TInput1 : AInput 
    where TInput2 : BInput
{

}

public YOutput GetResonse<TInput1, TInput2>(TInput1 input1, TInput2 input2, out ErrorOutput error)
    where TInput1 : CInput 
    where TInput2 : DInput
{

}