根据作为方法参数传递的运算符执行计算

问题描述 投票:0回答:1

我试图根据作为方法参数传递的运算符进行算术运算。我可以通过多种方式执行此操作,但问题是我有一个要操作的数据表。我无法传递特定的数据行,因为我有很多数据行要操作。

我所做的:我知道这可以以委托方式完成。就像答案中的那样 - https://stackoverflow.com/a/44333156

public int MainOperationSimplifeid(Func<int, int, int> operatoru)
{
    if (beforeoperation == 2)
    {
        a2 = Convert.ToInt32(textBox1.Text);
        textBox1.Text = "";
        result = operatoru(a1, a2);
        //   textBox1.Text = Convert.ToString(result);
        a1 = 0;
        a2 = 0;
    }
    beforeoperation++;
    return result;
}

我知道,我也可以通过使用枚举或开关甚至方法重载来实现这一点。但我的代码已经庞大且复杂,有多种支持方法。所以我不想增加更多的复杂性。

我需要什么:我可以这样做吗?

void MethodName(DataTable dt, int operand, char op)
{
   //few lines of code
   dt.SomeRowName1 = (double)dtRowValue op operand;
   //few lines of code
   dt.SomeRowName2 = (double)dtRowValue op operand;
   dt.SomeRowName3 = (double)dtRowValue op operand;
   //few lines of code
}

我想以一种非常通用的方式(代码可重用性)来实现这一点,而不是进行方法重载或切换不同的运算符并一次又一次地编写相同的代码行。

如果有人能帮助我,我将非常感激。预先感谢。

c# generics operators code-reuse
1个回答
0
投票

您可以通过反射搜索运算符方法,然后从中创建委托。

static Func<T, T, T> FindOperator<T>(string op)
{
    var m = typeof(T).GetMethods(BindingFlags.Static | BindingFlags.NonPublic)
                     .First(mi => mi.Name.EndsWith($"op_{op}"));
    return (Func<T, T, T>)Delegate.CreateDelegate(typeof(Func<T, T, T>), m);
}

// Usage
FindOperator<int>("Division")(7, 2);
FindOperator<double>("Addition")(7.1, 2.3);

如果您关心效率,可以缓存结果。

如果你想知道“op”可以取哪些值,请查看相应类型文档中长长的“Implements”列表 --> https://learn.microsoft.com/en-us/dotnet/api /system.int32.

通过指定操作符中每个参数的类型,可以更加通用。

static Func<TSelf, TOther, TResult> FindOperator<TSelf, TOther, TResult>(string op)
{
    var m = typeof(TSelf).GetMethods(BindingFlags.Static | BindingFlags.NonPublic)
                     .First(mi => mi.Name.EndsWith($"op_{op}"));
    return (Func<TSelf, TOther, TResult>)Delegate.CreateDelegate(typeof(Func<TSelf, TOther, TResult>), m);
}
© www.soinside.com 2019 - 2024. All rights reserved.