如果我有这门课程:
a
b
是b
的引用,还是a会复制引用a
指向的值?
如果它复制了值,我怎样才能b
引用b
和MailApp.sendEmail(recipient, subject,{attachments:[blob,blob1]} ,{htmlBody:html});
引用参数引用?(就像Java一样)
答案 0 :(得分:2)
a
是b
的引用,还是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,因此f
和MyFoo
都指向相同的内存地址,但它们是不同的变量。这意味着,如果我们执行以下操作
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; }
}