CSh*_*zie 9 c# type-conversion
我是C#的新手.我有一个Persons类和一个继承自Persons类的User类.我的控制台我在一个数组中输入用户.然后,我只需输入用户ID即可向用户数组中的用户添加注释.在我的Persons类中,我有这个函数,必须搜索此用户是否在users数组中.
public static Persons FindPerson(Persons[] persons, int noteid)
{
foreach (Persons person in persons)
if (person.ID == noteid) return person;
return null;
}
Run Code Online (Sandbox Code Playgroud)
在我的User类中,我有一个函数循环id的整个输入,直到它获得users数组中的id.
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.");
}
}
Run Code Online (Sandbox Code Playgroud)
一切正常,但我现在在if语句中的"return person"上收到此错误消息.
无法将类型'UserCustomerNotes.Persons'隐式转换为'UserCustomerNotes.User'.存在显式转换(您是否错过了演员?)
有人可以帮忙吗?提前致谢.
Dea*_*ing 15
因为a Person不是nessecarily a User,编译器无法将a隐式转换Person为a User.在您的特定情况下,因为您知道自己有一个Users 列表,所以您可以明确地告诉它,"我知道这Person实际上是一个User",具有以下内容:
if (person != null)
return (User) person;
Run Code Online (Sandbox Code Playgroud)
(User)如果实例实际上不是a User,则cast()将在运行时抛出异常,但由于您已经开始使用Users 的集合,因此您不必担心.
| 归档时间: |
|
| 查看次数: |
50131 次 |
| 最近记录: |