Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/292.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何返回变量";“字符串”;从;开关";?_C# - Fatal编程技术网

C# 如何返回变量";“字符串”;从;开关";?

C# 如何返回变量";“字符串”;从;开关";?,c#,C#,如何从“开关”返回变量“字符串” 有一种方法 public string ParsingAll(int i, string cssSelector, string attr) { try { string str1 = "def"; switch (i) { case 0: var items = document.QuerySelectorAll(cssSelector); str1 = items[0].Te

如何从“开关”返回变量“字符串”

有一种方法

public string ParsingAll(int i, string cssSelector, string attr) 
{
  try
  {
    string str1 = "def";
    switch (i)
    {
      case 0: 
        var items = document.QuerySelectorAll(cssSelector); 

        str1 = items[0].TextContent.Trim();

        break;
    }
        return str1;
  }
  catch (Exception ex)
  {
    string s = ex.Message;    
  }
}
我得到了错误
“并非所有代码分支都返回值”


如何从“开关”返回变量“字符串”

只需在捕获物中添加一个返回物(或在它之后添加一个返回物,该返回物将自行覆盖所有分支):


catch块中缺少return语句

通常,我希望在所有try-catch块中使用returnnull语句来避免这些问题

public string ParsingAll(int i, string cssSelector, string attr) 
{
  try
  {
    string str1 = "def";
    switch (i)
    {
      case 0: 
        var items = document.QuerySelectorAll(cssSelector); 

        str1 = items[0].TextContent.Trim();

        break;
    }
        return str1;
  }
  catch (Exception ex)
  {
    string s = ex.Message;    
    throw ;/// OR handle exception, log it, etc based on your requirements.
  }

  return null;
}

catch不会返回任何内容,但是
ParsingAll
方法要求您返回字符串

您可以按照建议返回null或引发异常:

catch (Exception ex)
{
    string s = ex.Message;
    throw;
}

catch块没有返回任何可能的重复项我很惊讶你竟然一路复制粘贴了这家伙的反向名称。哈哈。好了,现在有链接了。
catch (Exception ex)
{
    string s = ex.Message;
    throw;
}