如何在方法中使用param数组传递字符串参数? [英] how to pass string parameter with param array in method?
本文介绍了如何在方法中使用param数组传递字符串参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class ParamParmeters
{
public int sum(string name, params int[] marks)
{
int sum = 0;
foreach (int element in marks)
{
sum += element;
}
return sum;
}
}
class Program
{
static void Main(string[] args)
{
ParamParmeters pp = new ParamParmeters();
int result = pp.sum("ABC", 10, 20, 30);
Console.WriteLine(result);
}
}
我得到输出有60。我需要输出ABC 60
I just get the output has 60 . I need output has "ABC 60"
推荐答案
你不能从int
方法返回一个字符串!
试试这个:
You can't return a string from anint
method!
Try this:
public string sum(string name, params int[] marks)
{
int sum = 0;
foreach (int element in marks)
{
sum += element;
}
return string.Format("{0} {1}", name, sum);
}
然后:
And then:
string result = pp.sum("ABC", 10, 20, 30);
返回字符串,而不是返回
并在开头添加字符串参数:int
Instead of returning anint
, return astring
and add the string parameter at the start:
public string sum(string name, params int[] marks) // change "public int" into "public string"
{
int sum = 0;
foreach (int element in marks)
{
sum += element;
}
return String.Concat(name, " ", sum);
}
此外,如果您使用的是.NET 3.5或更高版本,则无需使用foreach获取总和循环,然后你可以使用总和 [ ^ ]方法:
Also, if you use .NET 3.5 or later, it is not necessary to take the sum using a foreach loop, then you can just use the Sum[^] method:
public string sum(string name, params int[] marks)
{
int sum = marks.Sum();
return String.Concat(name, " ", sum);
}
这篇关于如何在方法中使用param数组传递字符串参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文