我正在阅读这篇文章http://msdn.microsoft.com/en-us/library/d5x73970.aspx以了解我是否可以将我的函数限制为仅使用基本或有限的数据类型集。基本上我正在编写一个只适用于 int、double、float、single、string、DateTime 的函数。那么我怎样才能将我的通用功能限制在这个范围内呢?
问问题
168 次
3 回答
4
不,您不能将类型参数限制为仅特定类型的集合。最接近的方法是查看它们都有哪些共同接口,并将其限制为实现这些接口的类型。
例如:
public void Foo<T>() where T : IComparable, IConvertible, IComparable<T>,
IEquatable<T>
但是,它实际上仍然不会阻止实现所有这些接口的其他类型。(即便如此,它也必须是所涉及的所有接口的严格交集——例如,string
不实现IFormattable
or ISerializable
,所以那些不能在列表中。)
但是,您始终可以将这些接口用作第一个过滤器,然后使用 进行执行时检查typeof(T)
,如果它不在接受的集合中则抛出异常。
于 2013-09-05T06:03:44.857 回答
2
它们都是值类型..因此您可以将其限制为:
public void YourFunction<T>() where T : struct // struct means only value types
确实,这取决于您的用例..
编辑:
我没有意识到你被列入string
你的名单。我错过了那个..上面的方法不起作用。
于 2013-09-05T05:57:39.820 回答
0
列出的类型没有太多共同点。听起来使用泛型方法实现这一点的唯一原因是避免装箱或必须将返回值转换为特定类型。我会做类似以下的事情:
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();
}
// ...
}
}
于 2013-09-05T06:16:47.477 回答