当满足条件时,将字符串数组值作为返回类型字符串传递



我有一个模块,返回字符串数组"string[]"。它包含成功代码和作者名称。

var get_author = SetBookInfo(Id, Name);

此函数SetBookInfo返回响应代码和作者名称。我的条件是::

如果响应码是" success ",返回作者名"william"。("成功","威廉")

如果响应代码为"failed"则返回"failed"

public string GetAuthorName()
{
    var get_author = SetBookInfo(Id, Name); // returns string[]
    if (get_author != null && get_author.Length > 0)
        {
        // how to write the above logic
        }
    else
        return "problem in accessing the function";
}

我该怎么做?请验证我的方法是否正确。还有别的办法吗?请帮助。

public string GetAuthorName()
{
string []get_author = SetBookInfo(Id, Name); // returns string[]
if (get_author != null && get_author.Length > 0)
 {
   if(get_author[0].ToLower().Equals("success"))
      return get_author[1];
   else
     return "failed";
  }
else
    return "problem in accessing the function";
}

如果你想返回多个字符串,你可以返回List of strings

public List<string> GetAuthorName()
{
string []get_author = SetBookInfo(Id, Name); // returns string[]
List<string> list=new List<string>();
if (get_author != null && get_author.Length > 0)
 {
   if(get_author[0].ToLower().Equals("success"))
    {
     list.Add("success"); 
     list.Add(get_author[1]);
    }
   else
     list.Add("failed");
  }
else
    list.Add("problem in accessing the function");
 return list;
}

也许这就是你想要的:

public string GetAuthorName()
{
    var get_author = SetBookInfo(Id, Name); // returns string[]
    if (get_author != null && get_author.Length > 0)
        {
            if(get_author[0] == "success") return get_author[1]; //e.g. ["success", "william"], "william" will be returned
            else if (get_author[0] == "failed") return "failed";
        }
    else
        return "problem in accessing the function";
}

假设响应码索引为0,作者索引为1。

最新更新