2017-04-01 36 views
1

我从C++切换到C#,并试图学习这些方法。你能帮我创建一个方法,将2个变量作为用户的输入吗?在C++中,只需制作一个无效方法并在变量名称前添加&,如:void Input(int &a, int &b),这将在主函数中保存其值的任何更改。有没有办法在C#中做到这一点?从C#中的用户处获取输入的方法

+3

'&'是C#中的'ref'。 –

+0

或使用Tuple https://msdn.microsoft.com/en-us/library/system.tuple(v=vs.110).aspx – brykneval

+0

@brykneval:元组是只读的afaik。 –

回答

2

在C#中,你必须对C的T &x ++两种选择:

  • ref参数 - 这些具有相同的功能,为C++引用参数,并
  • out参数 - 这些允许将数据传回从一种方法,而不是方法。

在你的情况,out是比较合适的,因为它可以让你通过那些以前没有被转让变量:

void Input(out int a, out int b) { 
    ... // Read and assign a and b 
} 

您可以调用此方法是这样的:

// In C# 7 
Input(out int a, out int b);  
// Prior to C# 7 
int a, b; 
Input(out a, out b); 

请注意,与C++不同的是,C#要求您使用关键字out来标记它。

+0

对于输出参数,必须在函数成员正常完成之前为其分配一个值。 – brykneval

+0

对于OP的问题,“出”是正确的答案吗?他提到他想要改变用户输入的变量,这意味着变量已经被赋值。因此,'out'不起作用,应该使用'ref'? – Jurjen

+0

@brykneval权利,这正是执行输入的方法应该发生的。 – dasblinkenlight

1

您可以使用ref (C# Reference)来实现此目的。这等于C++ &引用。

一个例子:

class RefExample 
{ 
    static void Method(ref int i) 
    { 
     // The following statement would cause a compiler error if i 
     // were boxed as an object. 
     i = i + 44; 
    } 

    static void Main() 
    { 
     int val = 1; 
     Method(ref val); 
     Console.WriteLine(val); 

     // Output: 45 
    } 
} 

值得一提的是的ref在C#中的用法应当是不同于C++非常罕见的。请参阅Jon Skeet's关于参数传递的文章。

0

在C#可以通过引用ref keyword传递参数。所以,你可以定义你的方法,如:

public void Input (ref int foo, ref int bar) { 
    foo = 14; 
    bar = 25; 
}

呼叫与ref关键字方法以及:

int a = 0; 
int b = 0; 
Input(ref a, ref b); 
// now a = 14 and b = 25

您提到这传递通过引用明确(但好处是,语法上很明显这是通过引用)。