简体   繁体   English

c#string.length

[英]c# string.length

This simple code: 这个简单的代码:

    [HttpPost]
    public ActionResult Check(string chosen_username, string email) {
        var lang = RouteData.Values["lang"]; ViewBag.Language = lang;

        string un; string em;
        try {
            un = chosen_username; em = email;
        }
        catch { un = ""; em = ""; }

        string s = un.Length.ToString();
        ViewBag.test = s;

        return View();
    }

Throws the object reference not set to an instance of an object-exception (on the line that reads "string s = un.Length.ToString();" 抛出未设置为对象异常实例的对象引用(在读取“string s = un.Length.ToString();”的行上。

Could anybody help a C# newbie out please? 请问有人帮C#新手出去吗?

I think you did not initialize ViewBag object or it is null. 我认为你没有初始化ViewBag对象或它是null。
Try this 尝试这个

if (ViewBag != null)
    ViewBag.test = un.Length.ToString();

To be sure that problem is not in string (and it's not, believe me) try this 为了确保问题不在字符串中(并且它不是,请相信我)试试这个

string s = un.Length.ToString();

and use debugger to check that s is the one you expected. 并使用调试器检查s是您期望的那个。

EDITED after OP posted new code: OP发布新代码后编辑:
Simply: string un is null!! 简单地说:string un为null !! Try using 尝试使用

if (!String.IsNullOrEmpty(un))
    ViewBag.test = un.Length.ToString();
else {
    // Manage here the error
}

Object reference exception is referring to your ViewBag object, not your un.Length.ToString() value. 对象引用异常是指您的ViewBag对象,而不是您的un.Length.ToString()值。

The following should run fine: 以下应运行正常:

string un = "test"; string em = "test";
string test = un.Length.ToString();

you should get that null pointer exception if chosen_username is null, since you never initialized your un string variable, 如果chosen_username为null,你应该得到那个空指针异常,因为你从未初始化你的un string变量,

you should either: - check for null input - initialize your function local variables - assign them to avoid null as in : un = chosen_username ?? 你应该: - 检查空输入 - 初始化你的函数局部变量 - 分配它们以避免null,如: un = selected_username ?? string.Empty; 的String.Empty;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM