使用“params”的方法 在泛型类型定义中
这个问题让我思考如何编写一种需要包含类型参数的变量列表。
一种方法是接受 params Type[] 作为参数的一部分,例如:
public static bool IsOneOf(this object obj, params Type[] types)
{
return types.Contains(obj.GetType());
}
但是,使用有点冗长(例如 obj.IsOneOf(typeof(int), typeof( bool), typeof(double))),我想知道定义一个采用任意数量的泛型参数的方法的替代方法。 类似于:
public static bool IsOneOf<params TArgs[]>(this object obj)
{
// use TArgs here
}
对此的一种解决方案是使用 4.0 BCL 的 Tuple 类(它定义了一个公共接口 ITuple
以及 Tuple
、Tuple< ;T1, T2> 等)定义如下内容:
public static bool IsOneOf<TTypes>(this object obj) where TTypes : ITuple
{
Type tupleType = typeof(TTypes);
return tupleType.GetGenericArguments().Contains(obj.GetType());
}
然后可以像这样使用:
if (obj.IsOneOf<Tuple<int, bool, decimal>>()) { ... }
这里是否有性能考虑,或者是否有其他方法来实现此语法?
This question got me thinking on how one could approach writing a method that would need to contain a variable list of type parameters.
One approach would be to accept params Type[]
as part of the arguments, such as:
public static bool IsOneOf(this object obj, params Type[] types)
{
return types.Contains(obj.GetType());
}
However, the use is a little verbose (e.g. obj.IsOneOf(typeof(int), typeof(bool), typeof(double))
) and I am wondering about alternative approaches to defining one method taking an arbitrary amount of generic arguments. Something akin to:
public static bool IsOneOf<params TArgs[]>(this object obj)
{
// use TArgs here
}
One solution to this would be to use the 4.0 BCL's Tuple classes (it defines a common interface ITuple
as well as Tuple<T1>
, Tuple<T1, T2>
, etc) to define something like the following:
public static bool IsOneOf<TTypes>(this object obj) where TTypes : ITuple
{
Type tupleType = typeof(TTypes);
return tupleType.GetGenericArguments().Contains(obj.GetType());
}
It could then be used like this:
if (obj.IsOneOf<Tuple<int, bool, decimal>>()) { ... }
Are there performance considerations here, or are there an alternative methods to achieve this syntax?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以通过将循环展开到每个“数量”的特殊情况中来挤出一点额外的速度:
等等。
但是,您多久需要知道一个对象是否是一对不相关类型中的一个或另一个? 更不用说三个或更多了。 对我来说似乎是一个相当模糊的需求。
You could possible squeeze out a little extra speed by unrolling the loop into special cases for each "arity":
And so on.
But then, how often do you need to know if an object is one or the other of a pair of unrelated types? Let alone three or more. Seems quite an obscure need to me.