gpt4 book ai didi

C# 测试变量是否赋值

转载 作者:可可西里 更新时间:2023-11-01 08:17:43 24 4
gpt4 key购买 nike

我正在尝试编写 Linq MinBy 扩展方法

public static class Extensions
{
public static T MinBy<T>(this IEnumerable<T> source, Func<T,int> selector)
{
T min;
int? minKey = null;
foreach (var x in source)
{
var key = selector(x);
if (minKey == null || key < minKey)
{
minKey = key;
min = x;
}
}
if (minKey == null)
{
throw new ArgumentException("source should not be empty");
}
return min;
}
}

我认为我的逻辑是正确且可读的。但是我得到一个构建错误

Use of unassigned local variable 'min'

我该怎么办?我可以测试变量是否已分配吗?


说明:MinBy 函数可以回答以下问题。哪个数字 [-5, -2, 3] 的平方最小?

> new List<int>{-5,-2,3}.MinBy(x => x*x)
-2

.NET 的 Min 函数回答了不同的问题(这是最小的正方形)

> new List<int>{-5,-2,3}.Min(x => x*x)
4

最佳答案

您需要一个 min 的默认值,如下所示:

T min = default(T);

You can read more about default() on MSDN:

Given a variable t of a parameterized type T, the statement t = null is only valid if T is a reference type and t = 0 will only work for numeric value types but not for structs. The solution is to use the default keyword, which will return null for reference types and zero for numeric value types. For structs, it will return each member of the struct initialized to zero or null depending on whether they are value or reference types. For nullable value types, default returns a System.Nullable, which is initialized like any struct.

关于C# 测试变量是否赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11326279/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com