我应该在这里使用 ref 还是 out 关键字? [英] Should I use the ref or out keyword here?
问题描述
我有一个可能为 null 的对象,我会将其传递给设置其属性的方法.
I have an object that may be null, which I will pass to a method that will set its properties.
所以我的代码看起来像:
So my code looks like:
User user = null; // may or may not be null at this point.
SetUserProperties(user);
UpdateUser(user);
public void SetUserProperties(User user)
{
if(user == null)
user = new User();
user.Firstname = "blah";
....
}
所以我正在更新传递给 SetUserProperties 的同一个对象.
So I am updating the same object I pass into SetUserProperties.
我应该在我的方法 SetUserProperties 中使用 'ref' 关键字吗?
Should I use the 'ref' keyword in my method SetUserProperties?
推荐答案
了解对象和变量之间的区别很重要:
It's important to be aware of the difference between an object and a variable:
- 在某些情况下,您希望更新调用者的变量以引用新对象,因此您需要按引用传递语义.这意味着您需要
ref
或out
- 您需要读取变量的现有值以了解是否创建新对象.这意味着您需要
ref
而不是out
.如果您将其更改为out
参数,则您的if
语句将无法编译,因为user
不会在开始时明确分配方法.
- You want the caller's variable to be updated to refer to a new object in some cases, so you need pass by reference semantics. That means you need
ref
orout
- You need to read the existing value of the variable to know whether to create a new object or not. That means you need
ref
rather thanout
. If you changed it to anout
parameter, yourif
statement wouldn't compile, becauseuser
wouldn't be definitely assigned at the start of the method.
不过,我个人不确定这是一个不错的设计.您确定创建新对象的方法有意义吗?你不能在呼叫站点这样做吗?感觉有点别扭.
Personally I'm not sure this is a nice design, however. Are you sure that it makes sense for the method to create the new object? Can you not do that at the call site? It feels slightly awkward as it is.
使用 ref
的另一种替代方法(但仍可能在该方法中创建一个新用户)是返回适当的引用:
Another alternative to using ref
(but still potentially creating a new user within the method) would be to return the appropriate reference:
user = SetUserProperties(user);
...
public User SetUserProperties(User user)
{
if(user == null)
{
user = new User();
}
user.Firstname = "blah";
....
return user;
}
这篇关于我应该在这里使用 ref 还是 out 关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!