C#中函數是不具備返回多個值的功能,因此我們要實作類別似的功能,可從以下幾個方面考慮
- 在方法中傳入參數
- out/ref
- 返回數組
- 返回某個對象的執行個體
1.方法中傳入參數
using System;namespace MultiReturn{ class Arithmetic { class JiaJian { public double a; public double b; public double computing(string method) { switch (method) { case "+": return a + b; case "-": return a - b; default : return 00000;; } } }
}
}
主函數
static void Main(string[] args) { double c, d; JiaJian MyArithmetic = new JiaJian(); MyArithmetic.a = 3; MyArithmetic.b = 1; c = MyArithmetic.computing("+"); d = MyArithmetic.computing("-"); Console.WriteLine("{0},{1}",c,d); Console.ReadKey(); }
2,OUT/REF
using System;
namespace MultiReturn
{
class Arithmetic
{
class JiaJian
{
public
void computing(double a,double b,
out double c,out
double d)
{
c = a + b;
d = a - b;
}
}
static
void Main(string[] args)
{
double c,d;
JiaJian MyArithmetic = new JiaJian();
MyArithmetic.computing(3,
1, out c, out d);
Console.WriteLine("{0},{1}",c,d);
Console.ReadKey();
}
}
}
3、返回數組
傳回值數量較多的時候使用Array容易出現記憶體溢出的問題,因此考慮使用List<>;
而且使用List<object>還有可以返回任意類型資料的優點;
using System;using System.Collections.Generic;namespace MultiReturn{ class Arithmetic { class JiaJian { public double a, b; public List<object> computing() { List<object> result = new List<object>(); result.Add("四則運算"); result.Add(a + b); result.Add(a - b); return result; } } static void Main(string[] args) { List<object> outcome; JiaJian MyArithmetic = new JiaJian(); MyArithmetic.a = 3; MyArithmetic.b = 1; outcome = MyArithmetic.computing(); Console.WriteLine("{0}\n{1}\n{2}\n",outcome[0],outcome[1], outcome[2]); Console.ReadKey(); } }}
4,、返回某個對象的執行個體
using System;
using System.Collections.Generic;
namespace MultiReturn
{
class Arithmetic
{
class Example
{
public
double a, b;
public
string c;
}
class JiaJian
{
public
double a, b;
public Example computing()
{
Example example = new Example();
example.a = this.a +
this.b;
example.b = this.a -
this.b;
example.c = "四則運算";
return example;
}
}
static
void Main(string[] args)
{
JiaJian MyArithmetic = new JiaJian();
Example result = new Example();
MyArithmetic.a = 3;
MyArithmetic.b = 1;
result = MyArithmetic.computing();
Console.WriteLine("{0}\n{1}\n{2}\n", result.a, result.b, result.c);
Console.ReadKey();
}
}
}