gpt4 book ai didi

c# - 通用约束排除

转载 作者:太空狗 更新时间:2023-10-30 00:28:54 26 4
gpt4 key购买 nike

抱歉问了个愚蠢的问题

是否有可能以可以导出给定 T 的方式对泛型实现约束来自除某些 A、B、C 之外的任何引用类型(其中 A、B、C 是引用类型)。(即)

Where T : class except A,B,C

最佳答案

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

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)
));
}
}
}

关于c# - 通用约束排除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1731286/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com