c# - 无法从 'int' 转换为 'System.Predicate<int>'

标签 c#

如何解决这个问题? 或者,为什么会出现此错误。我究竟做错了什么。我知道数据类型存在一些问题,但为什么以及我可以做些什么来解决这个问题?

我的 C# 代码:

int[] nums = new int[5];

int i = 0;
while (i < 5)
{
    int num = Convert.ToInt32(Console.ReadLine());
    if (Array.Find(nums, num) != 0)
    {
        Console.WriteLine("Error: Number already inputed. Try a different number.");
        continue;
    }
    i++;
}```

Error:
*Severity   Code    Description Project File    Line    Suppression State
Error   CS1503  Argument 2: cannot convert from 'int' to 'System.Predicate<int>'    udemy lectures beginner section6 exercise   D:\C# practice\C# practice codes\exercises\udemy lectures beginner section6 exercise\udemy lectures beginner section6 exercise\Program.cs   104 Active*  (line 8)

最佳答案

您可以使用 lambda 语法创建谓词

var index = Array.Find (nums, n=> n == num); // n == num returns a bool

//array returns a position of a found item in array if item is found. If it is not found returns -1;

if ( index >= 0 )   // if found
{

// or shorter
if ( Array.Find (nums, n => n == num) >= 0 )   // if found
{
...

但它通常用于复杂对象的数组。例如,如果数组项不是 int,而是具有 Id 和 Name 属性的类,您可以使用它

var index=Array.Find (nums, n=> n.Id == num);

对于像你这样的简单数组,最好使用

if (Array.IndexOf(nums, num) != -1) // index of found item or -1 if not found
{
...

关于c# - 无法从 'int' 转换为 'System.Predicate<int>',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73093296/

相关文章:

c# - 如何在页面之间传递值? (Windows 手机)

c# - 使用 Mono.Cecil 通过 dll 获取静态只读字符串值?

c# - 如何使面板内的鼠标拖动从窗口移动?

c# - 从子类成员调用基类成员函数

c# - Web API 中的命名空间 'Http' 中不存在类型或命名空间 'System.Web'

c# - 如何在 UWP Windows 10 应用程序中将 InkCanvas 渲染为图像?

c# - 如何从pdf图像中查找文本?

c# - 如何在 ASP.net C# 中将 HTML 文本编辑器内容存储和检索到 SQL Server DB

c# - 带有 retrofit 的多部分内容

c# - azure 搜索服务和开放时间