通用约束排除 [英] Generic constraint exclusion

查看:205
本文介绍了通用约束排除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对不起,问愚蠢的问题。



是否有可能实施对泛型约束以这样的方式给定的T能够从任何引用类型派生
除了一些A,B,C(其中A,B,C是引用类型)。
(IE)

 其中T:除A,B,C 


解决方案

没有。但你可以检查这些类在运行时:

 公共类Foo< T> 
{
静态的Foo()
{
//这取决于你试图做
如果(typeof运算(A).IsAssignableFrom(什么下列情况之一typeof运算(T)))
{
抛出新NotSupportedException异常(的String.Format(
通用型美孚< T>不能与实例{0},因为它起源或器具{1} ,
的typeof(T),
typeof运算(A)
));
}

如果(typeof运算(T)== typeof运算(A))
{
抛出新NotSupportedException异常(的String.Format(
泛型类型美孚< T>不能使用类型{0},
typeof运算(A)
))进行实例化;
}
}
}


Sorry for asking silly question

Is it possible to enforce constraint on generic in such a way that the given T can be derived from any reference Type except some A,B,C (where A,B,C are reference types). (i.e)

Where T : class except A,B,C

解决方案

No. But you could check for these classes at run-time:

public class Foo<T>
{
    static Foo()
    {
        // one of the following depending on what you're trying to do
        if (typeof(A).IsAssignableFrom(typeof(T)))
        {
            throw new NotSupportedException(string.Format(
                "Generic type Foo<T> cannot be instantiated with {0} because it derives from or implements {1}.",
                typeof(T),
                typeof(A)
                ));
        }

        if (typeof(T) == typeof(A))
        {
            throw new NotSupportedException(string.Format(
                "Generic type Foo<T> cannot be instantiated with type {0}.",
                typeof(A)
                ));
        }
    }
}

这篇关于通用约束排除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆