如果变量C#试验分配变量、分配

2023-09-03 06:12:44 作者:灬莫欺少年穷丶

我想codeA的LINQ MinBy扩展方法

 公共静态类扩展
{
    公共静态牛逼MinBy< T>(这IEnumerable的< T>源,Func键< T,INT>选择器)
    {
        T最小;
        诠释? minKey = NULL;
        的foreach(VAR的X源)
        {
            VAR键=选择(X);
            如果(minKey == NULL ||钥匙< minKey)
            {
                minKey =键;
                分= X;
            }
        }
        如果(minKey == NULL)
        {
            抛出新的ArgumentException(来源不能为空);
        }
        返回分钟;
    }
}
 

我觉得我的逻辑是正确的和可读性。但我得到一个生成错误

  

使用未分配的局部变量最小

我能做些什么呢?我可以测试,如果变量分配?

澄清:在MinBy功能可以回答以下问题。其中编号[-5,-2,3]具有最小平方

 >新的List< INT> { -  5,-2,3} .MinBy(X => X * X)
-2
 
二 JAVA环境变量配置和测试JAVA变量是否配置成功

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

 >新的List< INT> { -  5,-2,3} .Min(X => X * X)
4
 

解决方案

您需要默认值最小是这样的:

T分=默认(T);

你可以阅读更多关于默认( ) MSDN上:

  

鉴于参数化类型T的一个变量t,语句T =空   只有有效的,如果T是引用类型和t = 0,将只工作   数值类型而不是结构。解决的方法是使用   默认的关键字,这将返回null引用类型和零   对于数值类型。对于结构,它将返回的每个成员   该结构初始化为零或为空,这取决于它们是否是   值或引用类型。对于空值类型,默认返回   System.Nullable,这就像任何结构进行初始化。

I'm trying to code a Linq MinBy extension method

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;
    }
}

I think my logic is correct and readable. But I get a build error

Use of unassigned local variable 'min'

What can I do about this? Can I test if the variable is assigned?

Clarification: A MinBy function can answer the following question. Which of the numbers [-5, -2, 3] has the smallest square?

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

.NET's Min function answers a different question (which is the smallest of the squares)

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

解决方案

You need a default value for min like this:

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.