我可以拥有可变数量的通用参数吗? [英] Can I have a variable number of generic parameters?
问题描述
在我的项目中,我有以下三个接口,它们由管理具有不同结构的各种业务对象的合并的类实现.
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 的关键部分.但是,您可以在旁边做一些事情,例如接受 Type[]
参数.您可能还会想出一些奇特的流畅的 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);
或使用泛型类型推断:
obj.Merge(firstData).Merge(secondData).Merge(thirdData).Execute(dest);
每个合并步骤都会简单地存储要做的工作,只能由 Execute
访问.
Each merge step would simple store away the work to do, only accessed by Execute
.
这篇关于我可以拥有可变数量的通用参数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!