我想从c#中的方法返回多个参数。我只是想知道哪个更好或者是元组?
static void Split (string name, out string firstNames, out string lastName)
{
int i = name.LastIndexOf (' ');
firstNames = name.Substring (0, i);
lastName = name.Substring (i + 1);
}
static Tuple<string,string> Split (string name)
{
//TODO
}
答案 0 :(得分:4)
如果需要从方法返回多个值,通常会有一个(值)类隐藏在某处。使用Split()
方法作为ctor的值类如何:
public class Name
{
public Name(string name)
{
int i = name.LastIndexOf (' ');
FirstNames = name.Substring (0, i);
LastName = name.Substring (i + 1);
}
public string FirstName {get; private set;}
public string LastName {get; private set;}
}
而不是
Split(name, out string firstName, out string lastName);
只是做
Name n = new Name(name);
并通过n.FirstName
和n.LastName
访问姓氏和名字。