将对象转换为字符串[]

时间:2014-07-16 17:31:50

标签: c# string return-value return-type

函数fixOutput格式化数据并在经过一些正则表达式后输出它

static object fixOutput(string data)
    {
        string user = "Unknown";
        string message = "";
        string command = "";
        string[] args = {};
        string newdata = Regex.Replace(data, @"!.+ :", ":");
        Regex nameExpr = new Regex(@":.*:");
        Match match = nameExpr.Match(newdata);

        if (match.Success)
        {
            user = Regex.Replace(match.Groups[0].Value,":", "");
            //Console.WriteLine(name);
        }
        message = Regex.Replace(newdata, ":.*:", "");

        Regex ComExpr = new Regex(@"\!.*");
        match = ComExpr.Match(message);

        if (match.Success)
        {
            command = match.Groups[0].Value;
        }
        return new string[] { user, message, command };

    }

然而,当我尝试这样做时:

string[] returnValue = fixOutput(data);

它说:     无法隐式转换类型'对象'到' string []'。存在显式转换(您是否错过了演员?)。

我不明白为什么我会收到这个错误,因为两者(据我所知)都是字符串[]

以下是一些示例输入数据:

:minijack!minijack@minijack.tmi.twitch.tv PRIVMSG #minijack :hello Kappa

5 个答案:

答案 0 :(得分:3)

您可以明确地将对象转换为string[]或使用as运算符,如:

string[] returnValue = fixOutput(data) as string[];

或者

string[] returnValue = string[](fixOutput(data));

更重要的是,为什么要在对象中返回字符串数组?您可以修改方法以返回字符串数组或IEnumerable<string>

答案 1 :(得分:1)

收听编译器消息:

  

它说:不能隐式转换类型&#39;对象&#39;到&#39; string []&#39;。 存在显式转换(您是否错过了演员?)。

尝试:

string[] returnValue = (string[]) fixOutput(data);

答案 2 :(得分:1)

当声明对象时,它表示它将返回一个对象,我将其更改为:

static string[] fixOutput(string data)

哪个有效,谢谢你的帮助。这是一个愚蠢的错误 谢谢cdmckay

答案 3 :(得分:0)

您无法隐式object投射到string[] - 您可以明确投射:

string[] returnValue = (string[])fixOutput(data);

或将函数的返回类型更改为string[]

答案 4 :(得分:0)

因为在方法声明中你已经指定将返回object,你实际上可以从该方法返回任何内容。

这是因为C#中的所有类都派生自System.Object。但是,当您将string[]作为对象返回时,如果要使用它,则需要明确告诉编译器将其强制转换为string[]

string[] output = (string[])fixOutput(data);

但是,正如其他人所提到的,如果您没有特定的理由退回string[],那么返回object会更好。

相关问题