Csharp/C#教程:通用约束排除分享


通用约束排除

很抱歉问愚蠢的问题

是否有可能以这样的方式强制执行约束,即给定的T可以从任何引用类型派生,除了一些A,B,C(其中A,B,C是引用类型)。 (即)

Where T : class except A,B,C 

不。但您可以在运行时检查这些类:

 public class Foo { 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 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 cannot be instantiated with type {0}.", typeof(A) )); } } } 

不,您只能指定它从特定类型inheritance,是值或引用类型,还是必须具有默认构造函数。 请记住,这是为了编译器的利益,而不是开发人员。 ?

您可能做的最好的事情是在运行时抛出exception。

对不起你可以了解如何限制在这里 ……

没有。没有类型的否定。 where子句仅允许您禁用特定类型。

上述就是C#学习教程:通用约束排除分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1004653.html

(0)
上一篇 2021年12月28日
下一篇 2021年12月28日

精彩推荐