如果我将对象传递给方法,为什么要使用ref关键字?这不是默认行为吗?
例如:
class Program
{
static void Main(string[] args)
{
TestRef t = new TestRef();
t.Something = "Foo";
DoSomething(t);
Console.WriteLine(t.Something);
}
static public void DoSomething(TestRef t)
{
t.Something = "Bar";
}
}
public class TestRef
{
public string Something { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
输出为"Bar",表示该对象作为参考传递.
我想知道是否有任何类似的东西可以用于价值类型......
public static class ExtensionMethods {
public static void SetTo(this Boolean source, params Boolean[] bools) {
for (int i = 0; i < bools.Length; i++) {
bools[i] = source;
}
}
}
Run Code Online (Sandbox Code Playgroud)
那么这是可能的:
Boolean a = true, b, c = true, d = true, e;
b.SetTo(a, c, d, e);
Run Code Online (Sandbox Code Playgroud)
当然,这不起作用,因为bools是一个值类型,因此它们作为值传递给函数,而不是作为引用.
除了将值类型包装到引用类型中(通过创建另一个类),有没有办法在使用params修饰符时通过引用(ref)将变量传递给函数?