【问题标题】:C# - Call a constructor from another constructor after some calculations [duplicate]C# - 在一些计算后从另一个构造函数调用构造函数[重复]
【发布时间】:2016-07-26 14:09:55
【问题描述】:

我有 2 个构造函数,接受不同类型的参数:

public someClass(String s) {

    // the string is parsed to an int array.
    int[] array = doSomething(s);

    this(array);
}

public someClass(int[] array) {
    doSomethingElse(array);
}

但是,在第一个构造函数中,我得到“方法名称是预期的”。有没有办法让构造函数在执行其他操作后调用另一个构造函数,还是仅仅是 C# 的限制?

【问题讨论】:

  • 两个构造函数都属于同一个class,在其他构造函数中做同样的事情有什么不同? (只是好奇)

标签: c# constructor


【解决方案1】:

你不能那样做。但是你可以写

public SomeClass(string s) : this(doSomething(s)){}

这很好,只要int[] doSomething(string)static

【讨论】:

    【解决方案2】:

    根据 Call one constructor from another

    public class SomeClass
    {
        public SomeClass(string s) : this(dosomething(s))
        {
    
        }
    
        public SomeClass(int[] something)
        {
        }
    
    
        private static int[] dosomething(string)
        {
            return new int[] { };
        }
    }
    

    我会使用静态方法来实现你想要的

    【讨论】:

      【解决方案3】:

      除非doSomething 是静态的。

      class someClass
      {
          public someClass(String s)
              : this(doSomething(s))
          { }
      
          public someClass(int[] array)
          {
              doSomethingElse(array);
          }
      
          static int[] doSomething(string s)
          {
              //do something
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2017-01-05
        • 1970-01-01
        • 2015-07-02
        • 2011-03-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-03
        • 1970-01-01
        相关资源
        最近更新 更多