用户输入的for循环中的数组错误 [英] array error in for loop on user input

查看:74
本文介绍了用户输入的for循环中的数组错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

private void button1_Click(object sender, EventArgs e)
        {
           BuildList(new object[] {1,tests,3});
        }



public string BuildList(object[] input)
            {
 string result = null;
            for (int i = 0; i < input.Length; i++)
            {
              if (input[i] != null)
                {

                   result = result + input[i].ToString() +  ",";
                }


                else
                {
                    result = "error";
                }
            }




            return result;
}

推荐答案

如果你想检查有效的数字,那么你可能最好是试用转换为你期望的实际数据类型。

所以如果你期望字符串形式的整数值,那么使用int.TryParse方法:

If you want to check for valid numbewrs, then you are probably best off doing a trial conversion to the actual datatype you are expecting.
So if you are expecting integer values in string form then use the int.TryParse method:
public string BuildList(object[] input)
    {
    StringBuilder result = new StringBuilder();
    foreach (object o in input)
        {
        string s = o as string;
        if (s != null)
            {
            int i;
            if (int.TryParse(s, out i))
                {
                result.AppendFormat("{0}, ", s);
                continue;
                }
            }
        return "Error";
        }
    return result.ToString();
    }

请注意,我已经更改了一些代码 - 其中一些代码用于编译代码(最后添加返回代码),一些代码使其更清晰(将 for 循环更改为 foreach )和一些更高效(使用StringBuilder而不是连接字符串) 。我也为你整理了缩进,所以更容易阅读...





hallo originalGriff谢谢你这么多你的回答问题是我必须处理空引用异常一个错误输入示例test我不知道输入的类型



试试这个:

Note that I have changed your code quite a bit - some of it to make your code compile (adding the return at the end), some to make it clearer (changing the for loop to a foreach) and some to make it more efficient (using a StringBuilder rather than concatenating strings). I also sorted out the indentation for you, so it is easier to read...


"hallo originalGriff thank you so much for your response the question is I have to handle the nullreference exception an the error input example"test" I do not know the type of the input"

Try this:

public string BuildList(object[] input)
    {
    StringBuilder result = new StringBuilder();
    foreach (object o in input)
        {
        if (o != null)
            {
            string s = o.ToString();
            if (s != null)
                {
                int i;
                if (int.TryParse(s, out i))
                    {
                    result.AppendFormat("{0}, ", s);
                    continue;
                    }
                }
            }
        return "Error";
        }
    return result.ToString();
    }


这篇关于用户输入的for循环中的数组错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆