[英]Can I modify a passed method parameter
my gut feeling says I shouldn't do the following.我的直觉告诉我不应该做以下事情。 I don't get any warnings about it.
我没有收到任何警告。
void test(DateTime d)
{
d = d.AddDays(2);
//do some thing with d
}
or is this more proper或者这更合适
void test(DateTime d)
{
DateTime _d = d.AddDays(1);
//do some thing with _d
}
For some reason I have always handled passed parameters like in the second example.出于某种原因,我总是像在第二个示例中那样处理传递的参数。 But I am not sure if it's really nessesry...maybe it's just unnessary code.
但我不确定它是否真的是 nessesry ......也许它只是 unnessary 代码。
I am not thinking that the calling method would be using the modified value.我不认为调用方法会使用修改后的值。 anyone have any opinions
任何人有任何意见
Changes to the value of a parameter are invisible to the caller, unless it's a ref
or out
parameter.对参数值的更改对调用者是不可见的,除非它是
ref
或out
参数。
That's not the case if you make a change to an reference type object referred to by a parameter.这是不是这样的,如果你改变一个引用类型的对象由参数引用。 For example:
例如:
public void Foo(StringBuilder b)
{
// Changes the value of the parameter (b) - not seen by caller
b = new StringBuilder();
}
public void Bar(StringBuilder b)
{
// Changes the contents of the StringBuilder referred to by b's value -
// this will be seen by the caller
b.Append("Hello");
}
Finally, if the parameter is passed by reference, the change is seen:最后,如果通过引用传递参数,则可以看到更改:
public void Baz(ref StringBuilder b)
{
// This change *will* be seen
b = new StringBuilder();
}
For more on this, see my article on parameter passing .有关更多信息,请参阅我关于参数传递的文章。
You can change it but the change will not go back to the caller.您可以更改它,但更改不会返回给调用者。
If it is a ValueType -> The copy of object is sent如果是ValueType -> 发送对象的副本
If it is a RefernceType -> Copy of Object reference will be sent by value.如果是ReferenceType -> 对象引用的副本将按值发送。 In this way properties of the object can be changed but not the reference itself - caller will not see the change anyway.
通过这种方式,可以更改对象的属性,但不能更改引用本身 - 调用者无论如何都不会看到更改。
If it is sent ref
-> Reference can be changed.如果发送
ref
-> 可以更改引用。
In C++ you can use const
to prevent the change but C# does not have that.在 C++ 中,您可以使用
const
来防止更改,但 C# 没有。 This is only to prevent the programmer by mistake try to change it - depending where the const
is used.这只是为了防止程序员错误地尝试更改它 - 取决于使用
const
位置。
If you want to be able to access the original value, use the second method.如果您希望能够访问原始值,请使用第二种方法。
If you don't care about the original value, you can use either one (I'd probably still use the second though).如果你不关心原始值,你可以使用任何一个(不过我可能仍然使用第二个)。
Either way, you're not going to hurt anybody else's values (even if you re-assign the value, it won't make it back to the caller) in this case.无论哪种方式,在这种情况下,您都不会损害其他任何人的值(即使您重新分配该值,它也不会返回给调用者)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.