泛型函数,其中T限制
本文关键字:限制 其中 函数 泛型 | 更新日期: 2023-09-27 18:30:10
我在读这篇文章http://msdn.microsoft.com/en-us/library/d5x73970.aspx以了解我是否可以将我的函数限制为仅使用基本或有限的数据类型集。基本上,我正在编写一个只适用于int、double、float、single、string和DateTime的函数。那么我如何将我的泛型函数限制为这个呢?
否,不能将类型参数仅约束为特定的类型集合。最接近的方法是查看它们有哪些共同的接口,并将其约束为实现这些接口的类型。
例如:
public void Foo<T>() where T : IComparable, IConvertible, IComparable<T>,
IEquatable<T>
然而,它仍然不会真正阻止实现所有这些接口的其他类型。(即使这样,它也必须是所有相关接口的严格交集——例如,string
没有实现IFormattable
或ISerializable
,所以这些接口不能在列表上。)
但是,您可以始终使用这些接口作为第一个过滤器,然后使用typeof(T)
执行执行时间检查,如果不在接受的集合中,则抛出异常。
它们都是值类型。。所以你可以限制它:
public void YourFunction<T>() where T : struct // struct means only value types
实际上,这取决于您的用例。。
编辑:
我没有意识到你把string
列入了你的名单。我错过了那个。。以上内容不适用于此。
列出的类型没有太多共同点。听起来,用泛型方法实现这一点的唯一原因是避免装箱或将返回值强制转换为特定类型。我会做以下事情:
public class Example
{
private static readonly HashSet<Type> supportedTypes = new HashSet<Type>
{
typeof(int),
typeof(double),
typeof(float),
typeof(string),
typeof(DateTime),
};
public T MyMethod<T>()
{
if (!this.supportedTypes.Contains(typeof(T))
{
throw new NotSupportedException();
}
// ...
}
}