我正在尝试创建一个通用的参数验证方法来检查集合参数是否为 null、空或包含 null 元素。
public void Foo(ICollection<MyType> bar)
{
// Validate parameters
ThrowIfNullEmptyOrContainsNull(bar, "bar");
.
.
.
如果我只指定 ICollection<T>
在类型约束中,然后是 if (value.Contains(null))
生成错误,因为 T
可能不是可为 null 的类型。
这是我想出来的,但似乎不对:
internal static T1 ThrowIfNullEmptyOrContainsNull<T1, T2>(T1 value, string name)
where T1 : ICollection<T2>
where T2 : class
{
if (ReferenceEquals(value, null))
throw new ArgumentNullException(name);
if (value.Count == 0)
throw new ArgumentException("Empty collection not allowed", name);
if (value.Contains(null))
throw new ArgumentException("Collection contains one or more null elements", name);
return value;
}
...但是我必须使用显式参数类型调用该方法,如下所示:
public void Foo(ICollection<MyType> bar)
{
// Validate parameters
ThrowIfNullEmptyOrContainsNull<(ICollection<MyType>, MyType>(bar, "bar");
.
.
.
如果没有在调用中明确指定 T1 和 T2,我会收到错误消息“无法从用法中推断出类型参数……”。
谁能阐明如何做到这一点?
最佳答案
只是不要使用Contains
。遍历集合并将值与 null
显式比较:
internal static T1 ThrowIfNullEmptyOrContainsNull<T1, T2>(T1 value, string name)
where T1 : ICollection<T2>
{
if (ReferenceEquals(value, null))
throw new ArgumentNullException(name);
if (value.Count == 0)
throw new ArgumentException("Empty collection not allowed", name);
foreach (var item in value)
if (item == null)
throw new ArgumentException("Collection contains one or more null elements", name);
return value;
}
关于c# - 如何指定 "collection of nullable types"的约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27258267/