【问题标题】:C# same method, but different parameters: with ref and withoutC# 方法相同,但参数不同:带 ref 和不带
【发布时间】:2014-10-24 09:19:45
【问题描述】:

我是意大利人,抱歉我的英语不好!我想知道是否有一种方法可以随时使用通过引用或值传递参数的方法。

例如,如果我想要这个方法:

public mehtod (ref int a)
{
    //do some stuff
}

还有这个方法

public method (int a)
{
    //do the same stuff of method(ref int a)
}

有没有一种方法可以获得相同的结果,但无需使用相同的主体创建两个不同的方法?我需要它是因为有时我希望使用“方法”产生副作用,有时我希望 a 不被修改!

非常感谢!

【问题讨论】:

  • 如果方法具有相同的主体,您一定不能使用 a 是 ref 参数这一事实,那么为什么要包含该版本呢?
  • @Andrew 这不是真的;您可以随时修改参数值 - 有趣的问题是:调用者 是否看到更改。这不会影响方法体
  • @MarcGravell:我想这是真的,很好。

标签: c# methods pass-by-reference pass-by-value


【解决方案1】:

您可以简单地从第二个方法调用第一个方法:

public void method (ref int a)
{
    //do some stuff
}

public void method(int a)
{
    method(ref a);  //do the same stuff of method(ref int a)
}

【讨论】:

  • 感谢您的回答,我在提出这个问题 3 秒后想到了相同的解决方案(但我在 15 分钟思考如何解决后问了这个问题)
  • 注意:这可能不适用于某些不喜欢仅在 ref 上重载的语言 - VB、IIRC
【解决方案2】:

如果返回类型为void,则可以将其改为return修改后的值,而不是使用ref。然后调用者可以根据自己的选择忽略返回值或使用返回值:

int Method(int foo) {
   // ...
   foo = ...
   // ...
   return foo;
}

与:

Method(a);

对比

a = Method(a);

【讨论】:

    【解决方案3】:

    我不确定你为什么要这样做.. 但有一种方法可以通过

    1. 在下面添加一个参数布尔标志来修改或不修改

    public mehtod (ref int a,bool modify)

    如果修改传递为假,则在其中声明一个新变量并仅分配该值并使用它 像 int b = a; 并根据您更新 ref 变量或保留它的标志在最后使用 b 进行处理

    【讨论】:

      【解决方案4】:
         static void callingMethod()
          {
              int a = 0;
              method(a); // original a is not modified
      
              // or
      
              method(ref a); // a is modified
          }
      
          static void method(int a)
          {
              method(ref a);
          }
      
          static void method(ref int a)
          {
              // do stuff
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-03-05
        • 2013-04-18
        • 1970-01-01
        • 1970-01-01
        • 2019-03-26
        • 2017-11-22
        • 2020-04-30
        相关资源
        最近更新 更多