通用函数,其中T限制

时间:2013-09-05 05:56:56

标签: c#

我正在阅读这篇文章http://msdn.microsoft.com/en-us/library/d5x73970.aspx,以了解我是否可以限制我的功能仅使用基本或有限的数据类型集。基本上我写的函数应该只适用于int,double,float,single,string,DateTime。那么如何限制我的通用功能呢?

3 个答案:

答案 0 :(得分:4)

不,您不能将类型参数限制为仅特定的类型集合。你最接近的是看它们共有哪些接口,并将它约束为实现这些接口的类型。

例如:

public void Foo<T>() where T : IComparable, IConvertible, IComparable<T>,
    IEquatable<T>
但是,它仍然不会实际阻止实现所有这些接口的其他类型。 (即便如此,它必须是所涉及的所有接口的严格交集 - 例如,string没有实现IFormattableISerializable,所以那些不能在列表)。

但是,您始终可以将这些接口用作第一个过滤器,然后使用typeof(T)执行执行时检查,如果它不在接受的集合中,则抛出异常。< / p>

答案 1 :(得分:2)

它们都是值类型..因此您可以将其限制为:

public void YourFunction<T>() where T : struct // struct means only value types

真的,这取决于你的用例..

编辑:

我没有意识到你在列表中包含了string。我错过了那一个......以上内容对此不起作用。

答案 2 :(得分: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();
        }

        // ...
    }
}