我的直觉告诉我不应该做以下事情。我没有收到任何关于它的警告。
void test(DateTime d)
{
d = d.AddDays(2);
//do some thing with d
}
还是这样更合适
void test(DateTime d)
{
DateTime _d = d.AddDays(1);
//do some thing with _d
}
出于某种原因,我总是像第二个示例那样处理传递的参数。 但我不确定它是否真的有问题……也许它只是一些不必要的代码。
我不认为调用方法会使用修改后的值。 大家有什么意见
最佳答案
参数值的改变对调用者是不可见的,除非是ref
或out
参数。
如果您对通过参数引用的引用类型对象进行更改,则不是这种情况。例如:
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");
}
最后,如果参数是通过引用传递的,则会看到变化:
public void Baz(ref StringBuilder b)
{
// This change *will* be seen
b = new StringBuilder();
}
有关此的更多信息,请参阅我的 article on parameter passing .
关于c# - 我可以修改传递的方法参数吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3991022/