c#可以优化这段代码吗?

Dan*_*986 0 c# optimization

我有一个按钮:

private void Button_Click(object sender, RoutedEventArgs e)
{
    string s = "x12y04";

    //make new instance for MyMath class
    MyMath dRet01 = new MyMath();

    //use the doubleArrayXY (in MyMath class) to get doubble array back
    double[] retD = dRet01.doubleArrayXY(s);

    //use the calcResultFromDoubleArray (in MyMath class) to get result
    MyMath dRet02 = new MyMath();
    double result = dRet02.calcResultFromDoubleArray(retD[0], retD[1]);

    //DEBUG!
    /*
    string TEST1 = Convert.ToString(returnedDouble[0]);
    MessageBox.Show(TEST1);
    string TEST2 = Convert.ToString(returnedDouble[1]);
    MessageBox.Show(TEST2);
    string TEST3 = Convert.ToString(result);
    MessageBox.Show(TEST3);
   */


}
Run Code Online (Sandbox Code Playgroud)

"MyMath"类是:

public double[] doubleArrayXY(string inputValue)
{
    //in case there are upper case letters, set all to lower
    string inpLow = inputValue.ToLower();

    //split the string on the Y (so this tech should also work for x89232y329)
    //so this will create res[0] that is x89232 and an res[1] that is 329
    string[] res = inpLow.Split(new string[] { "y" }, StringSplitOptions.None);

    //in the first string that looks like x89232, remove the x
    string resx = res[0].Replace("x", null);

    //now get the x value to a double
    double x = double.Parse(resx);
    //now get the y valye to a double
    double y = double.Parse(res[1]);

    //return in a double array the x and then the y (x=double[0] and y=double[1])
    return new double[] {x,y};
}

public double calcResultFromDoubleArray(double one, double two)
{
    return (one * two);
}
Run Code Online (Sandbox Code Playgroud)

现在我知道类中"calcResultFromDoubleArray"的部分在这一点上是没用的,但是我想稍后做一些额外的事情.

我最想知道的是在我创建这个新dRet10的主代码中,以及之后的make dRet02.

我一开始想我可以这样做:

double result = dRet01.calcResultFromDoubleArray(retD[0], retD[1]);
Run Code Online (Sandbox Code Playgroud)

因此,在这种情况下,我不需要创建MyMath的新实例,但这不起作用.

所以我需要为类调用一个新实例(就像我一样),或者我能以更优雅的方式执行此操作吗?我仍然是C#的新手,所以我试图学习如何以优雅和优雅的方式编程,除了让它工作.

Bro*_*ass 5

由于您的方法除了传递的参数之外没有真正使用任何其他状态信息,static因此它们可能应该是这样您根本不必创建任何类的实例:

double[] retD = MyMath.DoubleArrayXY(s);
double result = MyMath.CalcResultFromDoubleArray(retD[0], retD[1]);
Run Code Online (Sandbox Code Playgroud)

如果你的所有方法MyMath都是静态的,那么声明类本身就是静态的 - 就像System.Math类一样,所以你根本不能创建实例.