c# - 如何指定 "collection of nullable types"的约束?

标签 c# .net nullable generic-collections type-constraints

我正在尝试创建一个通用的参数验证方法来检查集合参数是否为 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/

相关文章:

c# - 如何使用新的任务并行库确保两个任务在不同的线程甚至不同的处理器上运行?

更新/删除空字段时Mysql级联

c# - .NET CLR 是否真的针对当前处理器进行了优化

.net - 从 XmlDocument 到 XmlDocument 的 XslCompiledTransform

c# - 如何获得执行程序集位置?

c# - 显示 TreeNode 的图像

java - @NotNull 是否在运行时工作

c# - 如何将类型 int[] 转换为 int?[]

c# - 在数据库或数据表中查询一列中的重复记录

c# - DataGridView 与 DataSource 一起使用时 "No row can be added to a DataGridView control that does not have columns. Columns must be added first."