简体   繁体   English

c# 8 可为空 + 字典<>

[英]c# 8 nullable + Dictionary<>

My code looks something like this:我的代码看起来像这样:

#nullable enable
class MyClass<KEY, ITEM>
{
    readonly Dictionary<KEY, ITEM> Map = new Dictionary<KEY, ITEM>();
    public void Process(KEY key, ITEM item)
    {
        if (key != null)
        {
            Map[key] = item;
        }
    }
}
#nullable disable

The compiler is not thrilled with this, it gives me the warning编译器对此并不感兴趣,它给了我警告

type 'KEY' cannot be used as type parameter 'TKey' in the generic type or method 'Dictionary<TKey, TValue>

which I can certainly understand.我当然可以理解。 The problem is, sending null for the 'key' parameter to Process() is perfectly valid so I can't add the "where KEY: notnull" constraint to the class.问题是,将“key”参数的 null 发送到 Process() 是完全有效的,因此我无法将“where KEY: notnull”约束添加到 class。 (and MyClass needs to accept both classes and structs for the KEY type parameter) (并且 MyClass 需要接受 KEY 类型参数的类和结构)

The only thing I can think of is this:我唯一能想到的是:

#nullable enable
class MyClass<KEY, ITEM>
{
#nullable disable
    readonly Dictionary<KEY, ITEM> Map = new Dictionary<KEY, ITEM>();
#nullable enable
    public void Process(KEY key, ITEM item)
    {
        if (key != null)
        {
            Map[key] = item;
        }
    }
}
#nullable disable

Which keeps the compiler happy, but then I don't have all those nice C# 8 null checks.这让编译器很高兴,但是我没有所有那些好的 C# 8 null 检查。 For example, it allows me to write this code:例如,它允许我编写以下代码:

Map[default] = item;

and the compiler doesn't bat an eye.并且编译器不会眨眼。

How can I tell the compiler that the 'KEY' type parameter to Dictionary<> should disallow nulls, but still allow KEY values to be null in the outer class?如何告诉编译器 Dictionary<> 的 'KEY' 类型参数应该不允许空值,但仍然允许外部 class 中的 KEY 值是 null?

EDIT编辑

I want to use the new C# 8 nullability features so that I catch as many null pointers at compile time as possible (instead of waiting for runtime exceptions).我想使用新的 C# 8 可空性功能,以便在编译时捕获尽可能多的 null 指针(而不是等待运行时异常)。

FURTHER EDIT进一步编辑

The direction I'm headed right now, is to put a thin layer around Dictionary to enforce the null restrictions and use it instead of Dictionary<>我现在的方向是在 Dictionary 周围放置一个薄层以强制执行 null 限制并使用它而不是 Dictionary<>

#nullable enable
public class CheckDictionary<KEYTYPE, VALUETYPE>
{
#nullable disable
    readonly Dictionary<KEYTYPE, VALUETYPE> Dictionary = new Dictionary<KEYTYPE, VALUETYPE>();
#nullable enable

    public VALUETYPE this[[DisallowNull] KEYTYPE key]
    {
        get { return Dictionary[key]; }
        set { Dictionary[key] = value; }
    }

    public bool Remove([DisallowNull] KEYTYPE key)
    { return Dictionary.Remove(key); }

    public bool TryGetValue([DisallowNull] KEYTYPE key, out VALUETYPE value)
    { return Dictionary.TryGetValue(key, out value); }

    public List<VALUETYPE> Values => Dictionary.Values.ToList();
}

I think that in your case the next approach can be used:我认为在您的情况下可以使用下一种方法:

  • Constrain type parameter TKey to be notnull .将类型参数TKey约束为notnull As a result the compiler will enfoce null checks against TKey .因此,编译器将对TKey强制执行 null 检查。
  • Add AllowNullAttribute to the parameter TKey key of the method Process .AllowNullAttribute添加到方法Process的参数TKey key As a result code that passes null key to the method Process will not produce warnings.因此,将null key传递给方法Process的代码不会产生警告。

Here is the code with comments:这是带有注释的代码:

class MyClass<TKey, TItem> where TKey : notnull
{
    // With "notnull" constraint type parameter "TKey" matches type constraint
    // of the class Dictionary<TKey, TValue>, therefore compiler does not
    // generate the next warning:
    //   The type 'TKey' cannot be used as type parameter 'TKey' in the 
    //   generic type or method 'Dictionary<TKey, TValue>'. Nullability
    //   of type argument 'TKey' doesn't match 'notnull' constraint.
    readonly Dictionary<TKey, TItem> Map = new Dictionary<TKey, TItem>();

    public void Process([System.Diagnostics.CodeAnalysis.AllowNull] TKey key, TItem item)
    {
        // "TKey key" is marked with [AllowNull] attribute. Therefore if you delete
        // null check "key != null" compiler will produce the next warning on the line
        // "Map[key] = item":
        //   Possible null reference argument for parameter 'key' in
        //   'TItem Dictionary<TKey, TItem>.this[TKey key]'.
        if (key != null) 
            Map[key] = item;

        // Because "TKey" is constrained to be "notnull", this line of code
        // produces the next warning:
        //   Possible null reference argument for parameter 'key' in
        //   'TItem Dictionary<TKey, TItem>.this[TKey key]'.
        Map[default] = item;
    }
}

static class DemoClass
{
    public static void Demo()
    {
        MyClass<string, int> mc1 = new MyClass<string, int>();
        // This line does not produce a warning, because "TKey key" is marked
        // with [AllowNull] attribute.
        mc1.Process(null, 0);
        // This line does not produce a warning too.
        mc1.Process(GetNullableKey(), 0);

        // Usage of "MyClass" with value type "TKey" is also allowed.
        // Compiler does not produce warnings.
        MyClass<int, int> mc2 = new MyClass<int, int>();
        mc2.Process(0, 1);
    }

    public static string? GetNullableKey() => null;
}

So using such approach we:因此,使用这种方法,我们:

  • enfoced null checks against TKey in the MyClass ;强制 null 检查MyClass中的TKey
  • allowed to pass null key to the Process method without getting warnings.允许将null key传递给Process方法而不会收到警告。

I found the same problem, my solution is to wrap the keys in a 1-tuple:我发现了同样的问题,我的解决方案是将密钥包装在一个 1 元组中:

class MyClass<TKey, TItem>
{
    readonly Dictionary<ValueTuple<TKey>, TItem> Map = new Dictionary<ValueTuple<TKey>, TItem>();

    public void Process(TKey key, TItem item)
    {
        Map[ValueTuple.Create(key)] = item;
    }
}

In this way any value can be added to the dictionary (ie null) and the compiler is satisfied without disabling rules.通过这种方式,可以将任何值添加到字典中(即 null),并且编译器在不禁用规则的情况下得到满足。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM