加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 将类型字符串转换为类型对象

发布时间:2020-12-16 00:14:13 所属栏目:百科 来源:网络整理
导读:我是C#的新手.我需要在控制台应用程序中显示用户fullname,但我一直收到此错误 Cannot implicitly convert type ‘string’ to ‘UserCustomerNotes.User’ 当我只使用返回用户时我的代码工作,但它在应用程序中显示的所有内容都是“UserCustomerNotes.User”,
我是C#的新手.我需要在控制台应用程序中显示用户fullname,但我一直收到此错误

Cannot implicitly convert type ‘string’ to ‘UserCustomerNotes.User’

当我只使用返回用户时我的代码工作,但它在应用程序中显示的所有内容都是“UserCustomerNotes.User”,我需要显示用户的全名.谁能请帮忙.这是我的代码:

public static User FindUser(User[] users,int noteid)
{
    foreach (User user in users)                
        if (user.ID == noteid) return user.FullName;
    return null;
}

解决方法

你的代码:

public static User FindUser(User[] users,int noteid)
{       
    foreach (User user in users)                
        if (user.ID == noteid) return user.FullName;
    return null;
}

期望在成功找到一个字符串对象时返回一个字符串对象(user.FullName值),而您为方法声明的返回类型是User.你应该做的就是这个(你当前正在调用FindUser的地方:

var ArrayOfUsersToSearch = GetAnArrayOfUserFromSomewhere();
var noteId = 3; // Or whatever value you want to use
var myUserToFind = FindUser(ArrayOfUsersToSearch,noteId);

Console.WriteLine("The users full name is: {0}",myUserToFind != null ? myUserToFind.FullName : "Not Found");

并将FindUser方法中的代码更改为:

public static User FindUser(User[] users,int noteid)
{       
    foreach (User user in users)                
        if (user.ID == noteid) return user;
    return null;
}

从方法返回用户时看到“UserCustomerNotes.User”输出的原因是:

Console.WriteLine(FindUser(users,noteId));

// instead of

Console.WriteLine(FinderUser(users,noteId).FullName);

因为返回类型是UserCustomerNotes.User并且它没有覆盖“ToString”来指定任何不同的东西,所以当Console.WriteLine询问User对象的文本等效项时给出的默认值是它的名称.这解释了为什么您当前看到代码中的“奇数”输出.

Note: I’ve put Console.WriteLine("The users full name is: {0}",myUserToFind != null ? myUserToFind.FullName : "Not Found"); as your code can return null if it fails to find a user and you’d want to special-case the output you provide in that circumstance.

它也值得一提,但与问题本身无关,格式为:

foreach(var x in y)
    do something;

如果在行下方进行更改,则比在每个语句块周围显式调出{和}时更容易“破坏”:

foreach (User user in users)                
{
    if (user.ID == noteid) 
    {
        return user.FullName;
    }
}
return null;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读