Cannot implicitly convert type 'customtype' to 'othercustomtype'

前端 未结 5 856
鱼传尺愫
鱼传尺愫 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

    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;
    

    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.

提交回复
热议问题