C#函数如何实现类似多个返回值的功能
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(); } } }
综上
方法一较为直观,但仅能返回同种类型的数据,有很大局限性;
2、3、4方法都有自己的特色。。