我可以修改传递的方法参数

Bra*_*rad 9 c#

我的直觉是说我不应该做以下事情.我没有得到任何关于它的警告.

void test(DateTime d)
{
 d = d.AddDays(2);
//do some thing with d
 }
Run Code Online (Sandbox Code Playgroud)

或者这更合适

 void test(DateTime d)
 {
 DateTime _d = d.AddDays(1);
//do some thing with _d
 }
Run Code Online (Sandbox Code Playgroud)

出于某种原因,我总是像第二个例子那样处理传递的参数.但我不确定它是否真的很麻烦...也许这只是一个无所不在的代码.

我不认为调用方法将使用修改后的值.任何人都有任何意见

Jon*_*eet 18

除非是a 或参数,否则对参数值的更改对调用者是不可见的.refout

这是不是如此,如果你改变一个引用类型的对象称为一个参数.例如:

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");
}
Run Code Online (Sandbox Code Playgroud)

最后,如果通过引用传递参数,则会看到更改:

public void Baz(ref StringBuilder b)
{
    // This change *will* be seen
    b = new StringBuilder();
}
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅我关于参数传递的文章.

  • 感谢您的文章...今晚我将在航班上阅读 (2认同)

Ali*_*tad 5

您可以更改它,但更改不会返回给调用者。

如果是ValueType ->发送对象的副本

如果它是ReferenceType ->对象引用的副本将按值发送。通过这种方式,可以更改对象的属性,但不能更改引用本身 - 调用者无论如何都不会看到更改。

如果发送ref-> 参考可以更改。

在 C++ 中,您可以使用const来阻止更改,但 C# 没有。这只是为了防止程序员错误地尝试更改它 - 取决于const使用的位置。