相关疑难解决方法(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万
查看次数

为什么引用类型不会在C#中更新

这是我的c#代码.为什么引用类型不在C#中更新,下面是代码

 class Program
    {
        public static void Main(string[] args)
        {
            var a = A.field;
            A.field = "2";

            Console.WriteLine(a);
            Console.Read();
        }
    }
    public static class A
    {
        public static string field = "1";
    }
Run Code Online (Sandbox Code Playgroud)

结果是1,为什么?

c# static

2
推荐指数
1
解决办法
300
查看次数

标签 统计

c# ×2

.net ×1

pass-by-reference ×1

ref ×1

static ×1