我能有一个可变数量的泛型参数? [英] Can I have a variable number of generic parameters?

查看:915
本文介绍了我能有一个可变数量的泛型参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的项目,我有以下三个接口,它是由管理合并多种具有不同结构的业务对象的类实现的。

In my project I have the following three interfaces, which are implemented by classes that manage merging of a variety of business objects that have different structures.

public interface IMerger<TSource, TDestination>
{
    TDestination Merge(TSource source, TDestination destination);
}

public interface ITwoWayMerger<TSource1, TSource2, TDestination>
{
    TDestination Merge(TSource1 source1, TSource2 source2, TDestination destination);
}

public interface IThreeWayMerger<TSource1, TSource2, TSource3, TDestination>
{
    TDestination Merge(TSource1 source1, TSource2 source2, TSource3 source3, TDestination destination);
}

这工作得很好,但我宁愿有一个 IMerger 接口,它指定了可变数量的 TSource 参数,这样的事情(例如下使用 PARAMS ;我知道这是不是有效的C#):

This works well, but I would rather have one IMerger interface which specifies a variable number of TSource parameters, something like this (example below uses params; I know this is not valid C#):

public interface IMerger<params TSources, TDestination>
{
    TDestination Merge(params TSource sources, TDestination destination);
}

这有什么办法可以做到这一点,什么功能上等同?

It there any way to achieve this, or something functionally equivalent?

推荐答案

您不能。这是API的一个关键部分。你可以,但是,做一些围绕在身边,如接受键入[] 参数。你可能也想了起来做了一些异国情调的流利的API /扩展方法的方式,但说实话它可能不会是值得的;但这样的:

You can't. That is a key part of the API. You could, however, do something around the side, such as accepting a Type[] argument. You might also think up some exotic "fluent API / extension method" way of doing it, but to be honest it probably won't be worth it; but something like:

obj.Merge<FirstType>(firstData).Merge<SecondType>(secondData)
     .Merge<ThirdType>(thirdData).Execute<TDestination>(dest);

或泛型类型推断:

or with generic type inference:

obj.Merge(firstData).Merge(secondData).Merge(thirdData).Execute(dest);

每个合并步骤将简单的存储客场做的工作,只能由进入执行

Each merge step would simple store away the work to do, only accessed by Execute.

这篇关于我能有一个可变数量的泛型参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆