相关疑难解决方法(0)

为什么在传递对象时使用'ref'关键字?

如果我将对象传递给方法,为什么要使用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",表示该对象作为参考传递.

.net c# ref pass-by-reference

269
推荐指数
7
解决办法
15万
查看次数

有趣的"参考参考"功能,任何解决方法?

我想知道是否有任何类似的东西可以用于价值类型......

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)将变量传递给函数?

c# extension-methods reference params

12
推荐指数
1
解决办法
5876
查看次数