gpt4 book ai didi

C# - 运算符返回类型

转载 作者:太空宇宙 更新时间:2023-11-03 18:08:06 25 4
gpt4 key购买 nike

关闭。这个问题需要details or clarity .它目前不接受答案。












想改进这个问题?通过 editing this post 添加详细信息并澄清问题.

7年前关闭。




Improve this question




我需要进行一些数学运算,例如:a+b、a-b、a/b、a*b 等等。

我想知道是否存在运算符返回类型,所以当我调用方法(返回运算符)以使用返回的数据(所以运算符)时。

如果不存在,我如何从字符串中获取该运算符。例如:

string myOperator = "+";
int a = 5, b = 10;
int outcome = 0;

我需要做:
outcome = a + b;

所以我需要那个 + 运算符。如果我创建一个以某种方式为我提供该运算符的方法,我应该使用什么作为返回类型?

最佳答案

不,运算符没有返回类型。但是,您可以使用 Func<T1,T2,R>制作一个具有运算符行为但具有函数语法的仿函数。

Func<int,int,int> myOperator1 = (x,y) => (x+y);
Func<int,int,int> myOperator2 = (x,y) => (x-y);
int a = 5, b = 10;
int outcome1 = myOperator1(a, b); // Returns 15
int outcome2 = myOperator2(a, b); // Returns -5

关于C# - 运算符返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22357435/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com