是否可以返回不同类型的多个值?

时间:2013-11-30 18:07:37

标签: c# javascript object return

在Javascript中,我可以创建一个返回对象的函数:

function person() {
  return { name: "John Doe", age: 20, isMarried: false };
}

console.log("Name: "+ person().name +". Age: "+ person().age +". Is married: "+ person().isMarried);

OUTPUT:
> "Name: John Doe. Age: 20. Is Married: false"

我想知道是否可以在C#中做这样的事情?我一直在阅读有关代表,词典和匿名方法的内容,但我仍然不知道这一点。

6 个答案:

答案 0 :(得分:6)

static void Main(string[] args)
{
    dynamic p = person();
    Console.WriteLine("Name: {0}, Age: {1}, Is married: {2}", p.name, p.age, p.isMarried);
}
static dynamic person()
{
    return new { name = "John Doe", age = 20, isMarried = false };
}

More info about the dynamic keyword

答案 1 :(得分:4)

您可以返回object

object Person() {
    var p = new ExpandoObject();
    p.Name = "John Doe";
    p.Age = 20;
    p.Married = false;

    return p;
}

你也可以创造更“动态”的东西:

object Person() {
    return new {
        Name = "John Doe",
        Age = 20,
        Married = false
    };
}

答案 2 :(得分:2)

您可以使用此

public void method(out string Name, out int Age, out bool Married){
    //body of method
    }

答案 3 :(得分:2)

在.NET 4.5中,有一种称为TUPLE的东西。你可以用它。 欲了解更多信息..您可以点击链接。

http://msdn.microsoft.com/en-us/library/system.tuple(v=vs.110).aspx

答案 4 :(得分:2)

您还可以返回包含多个值的元组。

static void Main(string[] args)
{
    var tuple = GetItem()
    Console.WriteLine(string.Format("Item1: {0}", tuple.Item1));
    Console.WriteLine(string.Format("Item2: {0}", tuple.Item2));
}

public static Tuple<string, int> GetItem()
{
    return new Tuple<string, int>("Some item from database.", 4);
}

答案 5 :(得分:0)

class Program
{
    static void Main(string[] args)
    {
        Tuple<int, string, double, string> emp = GetEmployeeInfo();
        Console.WriteLine("Emplooyee Id :: " + emp.Item1);
        Console.WriteLine("Employee Name :: " + emp.Item2);
        Console.WriteLine("Employee Salary :: " + emp.Item3);
        Console.WriteLine("Employee Address :: " + emp.Item4);
    }

    static Tuple<int, string, double, string> GetEmployeeInfo()
    {
        Tuple<int, string, double, string> employee;
        employee = new Tuple<int, string, double, string>(1001, "Uthaiah Bollera", 4500000.677, "Bangalore Karnataka!");
        return employee;
    }
}