This question already has answers here:
Return multiple values to a method caller

(26 个回答)


7年前关闭。




c#/.net 中是否需要多个返回参数?
public string, string GetFirstNameAndLastName(int id)
{
    var person = from p in People
                 where p.Id = id
                 select p;
    return(p.FirstName, p.LastName);
}

用法:
public void Main(string[] args)
{
    string firstName, lastName;
    (firstName, lastName) = GetFirstNameAndLastName(1);

    Console.WriteLine(firstName + ", " + lastName);
}

最佳答案

根据 @James Webster 的建议,您可以使用元组,也可以使用 dynamicExpandoObject

class Program
{
    static void Main(string[] args)
    {
        var d = GetUserDynamic();
        Console.WriteLine("{0}.{1}", d.FirstName, d.LastName);
    }

    private static dynamic GetUserDynamic()
    {
        dynamic d = new ExpandoObject();
        d.FirstName = "amandeep";
        d.LastName = "tur";
        return d;
    }
}

关于具有多个返回参数的 C# 方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5561470/

10-16 08:56