【问题标题】:customized arguments自定义参数
【发布时间】:2011-11-09 12:09:02
【问题描述】:

我在 c# 中创建了一个非常简单的向量 - 轴类。

通常它的工作方式类似于MyAxis abc = new MyAxis(p,x,y,z);(p 点)和(x,y,z 双打);

但是我想以我自己的方式调用构造函数,例如

MyAxis abc = new MyAxis([0 0 0],[0 0 1]); // Looks like MatLab;

我知道我可以通过字符串操作或列表或其他方式来做到这一点,但我想避免创建新对象并将它们传递给构造函数。

我还想避免..new MyAxis(a,b,c,d,e,f)...new MyAxis(new Point(x,y,z),...); 之类的东西

C#有这种可能性吗?

【问题讨论】:

  • 您不需要“自定义参数”,您需要自定义语法来创建对象 - 答案是“否”。

标签: c# function arguments


【解决方案1】:

您希望更改 C# 使用的语法,但这是不可能的。我相信你会得到最接近的是类似

MyAxis abc = new MyAxis(new []{0,0,0}, new[]{0,0,1});

但这并不是您想要的。不过,我认为这是你能得到的最好的结果。

【讨论】:

    【解决方案2】:

    你无能为力,除非你传入一个双精度数/整数数组

    new MyAxis(new int[]{1, 2, 3},new int[]{1, 2, 3});
    

    或者像你说的一个新对象,比如 new Point (x, y, z)(我知道你说过你想避免这种情况,但是使用 OO 语言,它确实“有效”)

    new MyAxis (new point(1, 2, 3), new point(5, 6, 7));
    

    【讨论】:

      【解决方案3】:

      让你的构造函数看起来像MyAxis(double[] p, double[] v)

      然后你可以像这样初始化你的对象:

      MyAxis abc = new MyAxis({0, 0, 0},{0, 0, 1}); // Looks _almost_ like MatLab;

      您的构造函数显然应该验证数组包含 3 个元素(或至少元素数量相等并支持 N 维向量)

      【讨论】:

      • 这个语法对我不起作用。您需要在每个传递的数组前面加上 new[] 才能让编译器满意。
      • 你可能是对的......你可以使用 double[] a = {0,0,1} 但它只适用于这样的初始化命令。最近javascript太多了...
      【解决方案4】:

      你可以试试这样的:

          MyAxis abc = new MyAxis(new[] { 0, 0, 0 }, new[] { 0.1, 0.2, 1.1} );
      

      然后在 MyAxis 的构造函数中执行如下操作:

          public MyAxis(new int[] points, new double[] doubles)
          {
           Point p = new Point(points[0], points[1], points[2]);
      
           double x = doubles[0], 
           y = doubles[1], 
           z = doubles[2];
      
           ...
      
           }
      

      如果你愿意,你也可以创建多个构造函数。

          public MyAxis(int a, int b, int c, int d, int e, int f)
          {
          }
      
          public MyAxis(Point a, Point b)
          {
          }
      
          public MyAxis(Point p, double[] doubles)
          {
          }
      

      等等

      不幸的是,没有办法创建自定义语法:(

      【讨论】:

        【解决方案5】:

        这对你有用吗?

        public someClass( int[] input1, int[] input2 ) 
        
        someClass temp = new someClass(new int[] { 1, 0, 1 }, new int[] { 1, 0, 1 });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-01-26
          • 1970-01-01
          • 2021-01-09
          • 2014-09-18
          • 1970-01-01
          • 2014-01-18
          • 2014-12-09
          • 1970-01-01
          相关资源
          最近更新 更多