public static int getInfo(string info)
{
string inputValue;
int infor;
Console.WriteLine("Information of the employee: {0}", info);
inputValue = Console.ReadLine();
infor = int.Parse(inputValue);
return infor;
}在上面的代码中,我如何获取一个人的姓名(String)和薪水(Int)?规范是,我需要调用该方法两次才能检索信息。
发布于 2017-04-14 14:45:55
您可以单独传递它,如果您创建一个包含信息和薪水的类,则传递效果会更好
public static int getInfo(string info,int salary)或者创建一个类,
public class MyInfo
{
public int info { get; set; }
public int salary { get; set; }
}方法签名是这样的,
public static int getInfo(MyInfo info)如果希望同时返回字符串和整数,最好将方法签名更改为类MyInfo的类型
public static MyInfo getInfo(MyInfo info)发布于 2017-04-14 14:53:42
您可以让它返回一个包含两个值的元组,如下所示:
internal Tuple<int, string> GetBoth(string info)
{
string inputValue;
int infor;
Console.WriteLine("Information of the employee: {0}", info);
inputValue = Console.ReadLine();
infor = int.Parse(inputValue);
return new Tuple<int, string>( infor, inputValue );
}
internal void MethodImCallingItFrom()
{
var result = GetBoth( "something" );
int theInt = result.Item1;
string theString = result.Item2;
}发布于 2021-12-05 05:43:23
为了从一个方法返回多个值,我们可以使用元组或(DataType,DataType,..)。
元组是只读的。因此,只能在声明时通过构造函数赋值。
下面的例子是使用多种数据类型作为返回类型。其既能读又能写。
public (string, int) Method()
{
(string, int) employee;
employee.Item1="test";
employee.Item2=40;
return employee;
}您可以在主代码中调用上述方法,如下图所示:
static void Main(string[] args)
{
(string name,int age) EmpDetails = new Program().Method();
string empName= EmpDetails.name;
int empAge = EmpDetails.age;
//Not possible with Tuple<string,int>
EmpDetails.name = "New Name";
EmpDetails.age = 41;
}但是,最佳实践是使用具有属性的类,如上面的答案所述。
https://stackoverflow.com/questions/43406548
复制相似问题