Could someone explaine please i thought it get just passed by ref when i explicite do it with ref?
var user = new User { Name = "MyName" };
ChangeNameToOtherName(user); // After method call user.name is "OtherName" < confusing
ChangeNameToOtherName(ref user); // After method call user.name is "OtherName"
var name = "MyName";
ChangeNameToOtherName(name); // After method call name is "MyName"
ChangeNameToOtherName(ref name); // After method call name is "OtherName"
Run Code Online (Sandbox Code Playgroud)
The ref keyword allows you to change the reference of the passed parameter, i.e. change the parameter itself directly.
I assume your method body looks something like this:
void ChangeNameToOtherName(User user) {
user.Name = "Other name";
}
Run Code Online (Sandbox Code Playgroud)
在这里,您将传递对user类型实例的引用.更改此实例上的属性将修改原始实例.如果指定新对象,则在方法外部将不会显示更改:user = new User { Name = "Name" };
字符串在.NET中是不可变的,您无法修改现有实例.您只能为变量分配新实例.但是更改实例变量引用在函数外部是不可见的(除非ref当然通过).
将类实例传递给函数将使用对该实例的引用来调用该函数.您可以更改实例,但不能更改对该实例的引用.
| 归档时间: |
|
| 查看次数: |
66 次 |
| 最近记录: |