Mac*_*iek 15 c# const reference
在C++中,传递const引用是一种常见的做法 - 例如:
#include <iostream>
using namespace std;
class X
{
public :
X() {m_x = 0; }
X(const int & x) {m_x = x; }
X(const X & other) { *this = other; }
X & operator = (const X & other) { m_x = other.m_x; return *this; }
void print() { cout << m_x << endl; }
private :
int m_x;
};
void main()
{
X x1(5);
X x2(4);
X x3(x2);
x2 = x1;
x1.print();
x2.print();
x3.print();
}
Run Code Online (Sandbox Code Playgroud)
这个非常简单的例子说明了它是如何完成的 - 非常多.但是我注意到在C#中似乎并非如此.我必须在C#中传递const引用吗?我需要什么"ref"关键字?请注意,我知道并了解C#引用和值类型.
Cha*_*lie 23
回答问题的参考部分; 将变量传递给方法时,会创建该变量的副本.使用ref关键字将传递该变量的相同实例,以便该方法能够为调用者更新该变量.
很多人似乎认为这只适用于值类型,因为引用类型只是作为引用传递,因此ref关键字没有效果.但是,事实并非如此,引用以与值相同的方式传递给方法; 它被复制并创建了该引用的新实例.这意味着调用者将看到对象本身的修改,但不会看到对引用的修改.因此,如果您尝试将对象设置为null或新对象,则如果未使用ref关键字,调用方将不会看到此修改:
没有参考:
void UpdatePerson(Person person)
{
// Caller would see this change
person.Name = "Bob";
// Caller wouldn't see this change
person = null;
}
Run Code Online (Sandbox Code Playgroud)
随着参考
void UpdatePerson(ref Person person)
{
// Caller would see this change
person.Name = "Bob";
// Caller would see this change
person = null;
}
Run Code Online (Sandbox Code Playgroud)
Mar*_*wis 14
C#没有const对象的概念(即你无法修改的对象); 只有变量(即字段)可以是常量或只读 - 意味着您无法分配它们.
ref关键字在概念上将对变量的引用作为参数传递,即被调用者可以修改变量(而不仅仅是修改值).这对于原始类型(int,bool等)特别有用.
归档时间: |
|
查看次数: |
26285 次 |
最近记录: |