c# - 我可以修改传递的方法参数吗

标签 c#

我的直觉告诉我不应该做以下事情。我没有收到任何关于它的警告。

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
 }

出于某种原因,我总是像第二个示例那样处理传递的参数。 但我不确定它是否真的有问题……也许它只是一些不必要的代码。

我不认为调用方法会使用修改后的值。 大家有什么意见

最佳答案

参数的改变对调用者是不可见的,除非是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");
}

最后,如果参数是通过引用传递的,则会看到变化:

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/

相关文章:

c# - & 符号被 HTML 编码为 &。有什么办法可以防止这种情况?

c# - SDK 2.3 内的 StorageClient 1.7 库。会被支持吗?

c# - 智能 HTML 编码

c# - 无法加载文件或程序集“System.Threading.Tasks.Extensions,版本=4.2.0.1”

c# - 从字符串中删除背靠背的子字符串,但不是删除所有出现的子字符串 - c#

c# - 使用 POST 请求向 Jira API 发送 JSON 时出现 System.Net.WebException

c# - 是否可以以编程方式密码保护 excel 电子表格?

c# - BinaryReader.Dispose(bool disposing) 创建流的本地引用。为什么?

c# - 我如何查看已执行的查询?

c# - 将具有多个参数的函数作为参数传递