【发布时间】:2015-02-11 11:12:27
【问题描述】:
在 C# 中,Nullable<T> 类型不满足 where struct 泛型约束(而 AFAK 这在技术上是一个结构)。这可用于指定泛型参数必须是不可为空的值类型:
T DoSomething<T>() where T : struct
{
//...
}
DoSomething<int?>(); //not ok
DoSomething<int>(); //ok
当然,Nullable<T> 也不满足引用类型 where class 约束:
T DoSomething<T>() where T : class
{
//...
}
DoSomething<int?>(); //not ok
DoSomething<Foo>(); //ok
这是否可以定义一个约束,例如它必须是引用类型或值类型但不能为 Nullable 值类型?
类似这样的:
void DoSomething<T>() where T : class, struct //wont compile!
{
//...
}
DoSomething<int?>(); //not ok
DoSomething<int>(); //ok
DoSomething<Foo>(); //ok
【问题讨论】:
-
除了
Nullable<T>之外的所有内容?这很难。 -
你为什么要这样做?
-
据我所知,通用约束是不可能的,因此没有可用的编译时检查。但是,您可以在运行时检查实际类型。
-
你可以用重载和可选参数来做这件事,但这很讨厌。请参阅codeblog.jonskeet.uk/2010/11/02/… 如果您可以向我们提供有关您想要实现的目标的更多信息,我们可以为您提供更多帮助。
-
@sloth :我有一个
Add<TValue>(Func<TViewModel, TValue> expression)方法,我想确保它只用于不可为空的类型(例如:Add(x => x.Id)OKAdd(x => x.CreationDate.Value)OKAdd(x => x.CreationDate)NOK) .
标签: c# generics nullable non-nullable generic-constraints