Cannot implicitly convert type 'customtype' to 'othercustomtype'

前端 未结 5 863
鱼传尺愫
鱼传尺愫 2020-12-06 17:25

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

5条回答
  •  余生分开走
    2020-12-06 18:11

    Since User inherits from Person, you cannot implicitly convert any random Person to a User (though you can implicitly convert a User to a Person).

    Since you pass a User[] to FindPerson(users, id), you can be sure the returned person is indeed a User, so you can cast it like this:

    return (User)person;
    

    Edit: You might consider using generics on FindPerson to avoid the cast altogether.

    public static T FindPerson(IEnumerable persons, int noteid)
        where T : Person
    {
        foreach (T person in persons)
        {
            if (person.ID == noteid)
            {
                return person;
            }
        }
    
        return null;
    }
    
    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))
            {
                User person = Persons.FindPerson(users, id);
                if (person != null)
                {
                    return person;
                }            
            }
    
            Console.WriteLine("The User does not exist. Please try again.");                
        }
    }
    

提交回复
热议问题