无法将类型“ customtype”隐式转换为“ othercustomtype” [英] Cannot implicitly convert type 'customtype' to 'othercustomtype'

查看:122
本文介绍了无法将类型“ customtype”隐式转换为“ othercustomtype”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C#的新手。我有一个Persons类和一个从Persons类继承的User类。在我的控制台中,我以数组形式输入用户。然后,我可以通过仅输入用户ID向用户数组中的用户添加注释。在我的Persons类中,我具有此功能,该功能必须搜索此用户是否在users数组中。

I am new to C#. I have a Persons class and a User class which inherits from the Persons class. I my console I input a users in an array. Then I can add a note to a user that is in the users array by only entering the users id. In my Persons class i have this function that has to search if this user is in the users array.

public static Persons FindPerson(Persons[] persons, int noteid)
{
    foreach (Persons person in persons)
        if (person.ID == noteid) return person;
    return null;
}

在我的User类中,我有一个函数可以循环id的整个输入直到获得用户数组中的ID。

In my User class I have a function that loops the whole input of the id until it gets an id that is in the users array.

public static User SelectUser(User[] users)
{
    while (true)
    {
        Console.Write("Please enter the User id: ");
        string input = Console.ReadLine();
        int id;
        if (int.TryParse(input, out id))
        {
            Persons person = Persons.FindPerson(users, id);
            if (person != null) return person; // fail on "return person"                   
        }
        Console.WriteLine("The User does not exist. Please try again.");                
    }
}

一切正常,除了我现在收到此错误消息

Everything works fine except that I now get this error message on the "return person" in the if statement.


不能将类型'UserCustomerNotes.Persons'隐式转换为'UserCustomerNotes.User'。存在显式转换(您是否缺少强制转换?)

Cannot implicitly convert type 'UserCustomerNotes.Persons' to 'UserCustomerNotes.User'. An explicit conversion exists (are you missing a cast?)

有人可以帮助吗?

推荐答案

因为不一定是 User ,编译器无法将 Person 隐式转换为 User 。在您的特定情况下,由于您知道您有一个 User s列表,因此您可以明确地告诉它,我知道这个人员实际上是具有以下内容的用户

Because a Person is not nessecarily a User, the compiler is not able to implicitly convert a Person to a User. In your particular case, since you know you have a list of Users, you can explicitly tell it, "I know this Person is actually a User" with the following:

if (person != null)
   return (User) person;

演员((用户))将如果实例实际上不是 User ,则在运行时引发异常,但是由于您已经从 User s开头,您不必担心。

The cast ((User)) will throw an exception at runtime if the instance is not actually a User, but since you've started with a collection of Users to begin with, you don't need to worry.

这篇关于无法将类型“ customtype”隐式转换为“ othercustomtype”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆