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

引用类型仍然需要通过ref?

请考虑以下代码(为简单起见,我没有遵循任何C#编码规则).

public class Professor
{
    public string _Name;

    public Professor(){}

    public Professor(string name)
    {
        _Name=name;
    }

    public void Display()
    {
        Console.WriteLine("Name={0}",_Name);
    }
}

public class Example
{
    static int Main(string[] args)
    {
        Professor david = new Professor("David");

        Console.WriteLine("\nBefore calling the method ProfessorDetails().. ");
        david.Display();
        ProfessorDetails(david);
        Console.WriteLine("\nAfter calling the method ProfessorDetails()..");
        david. Display();
    }

    static void ProfessorDetails(Professor p)
    {
        //change in the name  here is reflected 
        p._Name="Flower";

        //Why  Caller unable to see this assignment 
        p=new Professor("Jon");
    }
}
Run Code Online (Sandbox Code Playgroud)

正如预期的那样,输出是:

在调用方法之前,教授Details()......

姓名=大卫 …

c#

5
推荐指数
1
解决办法
6250
查看次数

标签 统计

c# ×2

.net ×1

pass-by-reference ×1

ref ×1