很抱歉问愚蠢的问题
是否有可能对泛型强制执行约束,使得给定的T可以从任何引用类型派生,除了一些A,B,C(其中A,B,C是引用类型).(即)
Where T : class except A,B,C
Run Code Online (Sandbox Code Playgroud)
不.但您可以在运行时检查这些类:
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)
));
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
576 次 |
| 最近记录: |