- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我是 C# 新手。我有一个 Persons 类和一个继承自 Persons 类的 User 类。在我的控制台中,我在一个数组中输入了一个用户。然后我可以通过仅输入用户 ID 向用户数组中的用户添加注释。在我的 Persons 类中,我有一个必须搜索此用户是否在用户数组中的函数。
public static Persons FindPerson(Persons[] persons, int noteid)
{
foreach (Persons person in persons)
if (person.ID == noteid) return person;
return null;
}
在我的 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.");
}
}
一切正常,除了我现在在 if 语句的“return person”上收到此错误消息。
Cannot implicitly convert type 'UserCustomerNotes.Persons' to 'UserCustomerNotes.User'. An explicit conversion exists (are you missing a cast?)
有人可以帮忙吗?提前致谢。
最佳答案
因为 Person
不一定是 User
,编译器无法将 Person
隐式转换为 User
。在您的特定情况下,由于您知道您有一个用户
列表,您可以明确地告诉它,“我知道这个人
实际上是User
"具有以下内容:
if (person != null)
return (User) person;
如果实例实际上不是 User
,则强制转换 ((User)
) 将在运行时抛出异常,但由于您是从 的集合开始的code>User
首先,您无需担心。
关于c# - 无法将类型 'customtype' 隐式转换为 'othercustomtype',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3757858/
我是 C# 新手。我有一个 Persons 类和一个继承自 Persons 类的 User 类。在我的控制台中,我在一个数组中输入了一个用户。然后我可以通过仅输入用户 ID 向用户数组中的用户添加注释
我是一名优秀的程序员,十分优秀!