通过引用传递变量

时间:2015-05-10 00:45:00

标签: c# reference

如果我有这门课程:

a

bb的引用,还是a会复制引用a指向的值? 如果它复制了值,我怎样才能b引用bMailApp.sendEmail(recipient, subject,{attachments:[blob,blob1]} ,{htmlBody:html}); 引用参数引用?(就像Java一样)

3 个答案:

答案 0 :(得分:2)

  

ab的引用,还是a会复制ref b指向的值?

取决于:

如果Boo是引用类型,如下所示,a将在调用后指向同一个实例

public class Boo
{
    public int Number { get; set; }
}

如果Boo是值类型,如下所示,a将是ref b指向的成员副本。

public struct Boo
{
    public int Number { get; set; }
}

答案 1 :(得分:0)

请参阅以下示例:

    public class Foo
    {
        public string Name { get; set; }
    }

    public class Bar
    {
        public Foo MyFoo { get; set; }

        public Bar(Foo paramFoo)
        {
            this.MyFoo = paramFoo;
        }
    }

这个序列:

        Foo f = new Foo();
        f.Name = "First Foo";

        System.Diagnostics.Debug.WriteLine(f.Name);

        Bar b = new Bar(f);

        System.Diagnostics.Debug.WriteLine(b.MyFoo.Name);

        b.MyFoo.Name = "Renaming Bar Name";

        System.Diagnostics.Debug.WriteLine(f.Name);
        System.Diagnostics.Debug.WriteLine(b.MyFoo.Name);

输出将是:

First Foo
First Foo
Renaming Bar Name
Renaming Bar Name

在这种情况下,我们将f引用传递给Bar ctor,因此fMyFoo都指向相同的内存地址,但它们是不同的变量。这意味着,如果我们执行以下操作

        b.MyFoo = new Foo();
        b.MyFoo.Name = "Yet another foo";

        System.Diagnostics.Debug.WriteLine(f.Name);
        System.Diagnostics.Debug.WriteLine(b.MyFoo.Name);

输出

Renaming Bar Name
Yet another foo

要更改此行为,您应该使用ref关键字,以便发送指向该变量的指针。

答案 2 :(得分:0)

通常使用ref关键字传递引用类型肯定存在差异。

以下代码应说明,请仔细阅读评论:

class Class6
{
    static void Main(string[] args)
    {
        Boo b = new Boo { BooMember = 5 };
        Console.WriteLine(b.BooMember);

        Foo f = new Foo(b);
        // b is unaffected by the method code which is making new object
        Console.WriteLine(b.BooMember);

        Foo g = new Foo(ref b);
        // b started pointing to new memory location (changed in the method code)
        Console.WriteLine(b.BooMember);
    }
}

public class Foo
{
    Boo a;
    public Foo(Boo b)
    {
        a = b;

        // b is just a reference, and actually is a copy of reference passed,
        // so making it point to new object, dosn't affect actual object , check in calling code
        b = new Boo();
    }

    public Foo(ref Boo b)
    {
        a = b;

        // b is just a reference, but actual reference itself is copied,
        // so making it point to new object would make the calling code object reference to point 
        // to new object. check in the calling code.
        b = new Boo();
    }
}

public class Boo
{
    public int BooMember { get; set; }
}