我们可以使用 2 个同名的 Func 吗?编译器不会抛出任何错误
Can we use 2 Func's with same name? Compiler doesn't throw any error
在下面的代码中,我创建了 2 个 Funcs 1)Class level 和 2) inside a method with same name and all same。当我构建解决方案时,它不会抛出任何错误并且执行得非常好。
现在我有兴趣调用 class 成员的 Func,但我不知道该怎么做。有人可以帮助我吗?
public class TaskDemo
{
public int NumberStrat { get; set; }
public int NumberEnd { get; set; }
Func<int, string> isNumerEvenOdd = (i) =>
{
return i.ToString();
};
public void print()
{
List<int> NumbersList = new List<int>();
for (int i = 0; i < 1000; i++)
{
NumbersList.Add(i);
}
Func<int, string> isNumerEvenOdd = (i) =>
{
return "abc";
};
Parallel.ForEach(NumbersList, (i) => Console.WriteLine(isNumerEvenOdd(i)));
}
}
使用这个关键字。
Parallel.ForEach(NumbersList, (i) => Console.WriteLine(this.isNumerEvenOdd(i)));
示例 -> https://onlinegdb.com/SkRpXyCRH
了解更多信息 -> https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/this
实际上,有一个警告(至少在 Resharper 中是这样),您的 Func<int, string> isNumerEvenOdd
本地声明隐藏了在 class 级别声明的 Func<int, string> isNumerEvenOdd
,并且从未使用过。因此,本地成员只是隐藏了 class 成员并且工作正常。
之所以没有编译错误,是因为你在不同的作用域(class和方法)定义了同名变量。当您尝试在同一范围内定义具有相同名称的变量时,编译器会显示错误
实际上使用 this
将解决您这里的问题 Parallel.ForEach(NumbersList, (i) => Console.WriteLine(this.isNumerEvenOdd(i)));
,正如之前的回答所说,因为在这种情况下,您指的是在 class 范围内定义的字段,而不是在方法中定义的字段范围。
The this
keyword refers to the current instance of the class
在下面的代码中,我创建了 2 个 Funcs 1)Class level 和 2) inside a method with same name and all same。当我构建解决方案时,它不会抛出任何错误并且执行得非常好。 现在我有兴趣调用 class 成员的 Func,但我不知道该怎么做。有人可以帮助我吗?
public class TaskDemo
{
public int NumberStrat { get; set; }
public int NumberEnd { get; set; }
Func<int, string> isNumerEvenOdd = (i) =>
{
return i.ToString();
};
public void print()
{
List<int> NumbersList = new List<int>();
for (int i = 0; i < 1000; i++)
{
NumbersList.Add(i);
}
Func<int, string> isNumerEvenOdd = (i) =>
{
return "abc";
};
Parallel.ForEach(NumbersList, (i) => Console.WriteLine(isNumerEvenOdd(i)));
}
}
使用这个关键字。
Parallel.ForEach(NumbersList, (i) => Console.WriteLine(this.isNumerEvenOdd(i)));
示例 -> https://onlinegdb.com/SkRpXyCRH
了解更多信息 -> https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/this
实际上,有一个警告(至少在 Resharper 中是这样),您的 Func<int, string> isNumerEvenOdd
本地声明隐藏了在 class 级别声明的 Func<int, string> isNumerEvenOdd
,并且从未使用过。因此,本地成员只是隐藏了 class 成员并且工作正常。
之所以没有编译错误,是因为你在不同的作用域(class和方法)定义了同名变量。当您尝试在同一范围内定义具有相同名称的变量时,编译器会显示错误
实际上使用 this
将解决您这里的问题 Parallel.ForEach(NumbersList, (i) => Console.WriteLine(this.isNumerEvenOdd(i)));
,正如之前的回答所说,因为在这种情况下,您指的是在 class 范围内定义的字段,而不是在方法中定义的字段范围。
The
this
keyword refers to the current instance of the class