相关疑难解决方法(0)

返回两个值,Tuple vs'out'vs'truct'

考虑一个返回两个值的函数.我们可以写:

// Using out:
string MyFunction(string input, out int count)

// Using Tuple class:
Tuple<string, int> MyFunction(string input)

// Using struct:
MyStruct MyFunction(string input)
Run Code Online (Sandbox Code Playgroud)

哪一个是最佳实践,为什么?

c# struct tuples out value-type

76
推荐指数
3
解决办法
2万
查看次数

创建具有可能为空的泛型键类型的字典

我正在编写一个通用方法,需要在内部使用Dictionary由通用参数键控的通用方法。

我不想对通用参数本身施加任何约束,特别是没有notnull约束。但是,该方法能够显式处理空值,当然不会向它使用的字典添加任何空键。

这样做有什么最佳实践吗?

默认情况下,编译器会警告通用键类型与 的notnull约束不匹配Dictionary<,>

请参阅下面的示例。除非我遗漏了什么,否则这应该是绝对安全的。但我怎样才能最好地将这一点传达给编译器呢?除了在这里抑制编译器警告之外,还有其他方法吗?

public static int CountMostFrequentItemOrItems<T>(params T[] values)
{
    var counts = new Dictionary<T, int>();  // The type 'T' cannot be used as type parameter 'TKey' in the generic type or method 'Dictionary<TKey, TValue>'
    var nullCount = 0;
    
    foreach(var value in values)
        if (value is null)
            ++nullCount;
        else if (counts.TryGetValue(value, out var count))
            counts[value] = count+1;
        else
            counts[value] = 1;

    // ... combine results etc ...
}
Run Code Online (Sandbox Code Playgroud)

c# dictionary nullable nullable-reference-types

9
推荐指数
0
解决办法
281
查看次数