在通用通用类中包含几种不同类型以进行公共访问?

时间:2010-10-27 21:12:33

标签: c# oop generics

我有几个Web服务可以返回各种结果。一些结果是字符串,一些是数组(从WSDL自动生成)。当我调用Web服务时,我想获得所有各种结果(包括异常),然后通过一个通用接口对它们进行操作,但由于类型不同,我无法使其工作。在下面的示例中,T是我想要存储的类型(例如List或string),U是服务返回的类型(例如Report []或string)。

    private class Result<T, U> : ICommon
    {
        public delegate U ResultProvider();

        public readonly string ElementName = null;
        public readonly T Value = null;
        public readonly Exception Exception = null;

        public Result(string ElementName, ResultProvider Provider)
        {
            this.ElementName = ElementName;
            try
            {
                this.Value = Provider();
            }
            catch (Exception e) {
                this.Exception = e;
            }
        }
    }

如果所有服务返回List,那么合并U和T并执行以下操作将是微不足道的:

    private class Result<T> : ICommon
    {
        public delegate T[] ResultProvider();

        public readonly string ElementName = null;
        public readonly List<T> Value = null;
        public readonly Exception Exception = null;

        public Result(string ElementName, ResultProvider Provider)
        {
            this.ElementName = ElementName;
            try
            {
                this.Value = new List<T>(Provider());
            }
            catch (Exception e) {
                this.Exception = e;
            }
        }
    }

但是当web方法返回非Array时,这将不起作用。所以现在我有Result<T>Result(有效手持编码的Result<string>版本)

对此设计有何建议?我应该看看哪种更好的模式?

2 个答案:

答案 0 :(得分:0)

我认为反思就是你想要的。

你可以使用typeof(U)来获取返回类型的ResultProvder,然后很容易弄清楚返回类型是什么并相应地处理它。你可以去做.IsArray然后.GetMethod来访问返回类型的成员。

答案 1 :(得分:0)

我不确定我是否完全理解你,但是在你的第一个例子中,你是否可以创建一个带有Func<U, T>的构造函数的重载,它将U转换为{{1} }} S'因此,如果服务返回T,则可以

Person[]

然后致电

public Result(string ElementName, ResultProvider Provider, Func<U, T> converter)
{
    this.ElementName = ElementName;
    try
    {
       this.Value = converter(Provider());
    }
    catch (Exception e) {
       this.Exception = e;
    }
 }
相关问题