如何返回方法 C#
我需要在运算符函数中返回一个方法。
public int Add()
{
return 1;
}
public static int operator +()
{
return Add;
}
我也需要对乘法、减法和除法运算符/函数执行此操作。
谢谢
I need to return a method in an operator function.
public int Add()
{
return 1;
}
public static int operator +()
{
return Add;
}
I will need to do this for a multiply, subtract and divide operator/function too.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您不能声明无参数运算符。您可以声明一个运算符来返回适当的委托 - 例如
Func
- 但在我看来,这将是一件非常奇怪的事情。如果您能告诉我们更多有关您想要实现的目标,我们可能会帮助您制定出更简洁的设计。
这是一个非常奇怪的重载一元 + 运算符的示例:
编辑:如果您只是尝试实现
Rational
类型,您更有可能想要:You can't declare parameterless operators. You can declare an operator to return an appropriate delegate - e.g.
Func<int>
- but it would be a pretty odd thing to do, IMO.If you can tell us more about what you're trying to achieve, we can probably help you to work out a cleaner design.
Here's a pretty strange example overloading the unary + operator:
EDIT: If you're just trying to implement a
Rational
type, you're more likely to want:这就是你似乎想要做的事情,但你的例子很难说清楚。因此,从您在其他答案中的评论来看,您似乎想要对有理数进行加、减、乘、除,这意味着结果也应该是有理数(而不是 int)。
因此,您可以定义每个方法,然后实现运算符来调用这些方法。运算符始终是静态的,因此您需要检查
null
并进行适当的处理(在本例中,我将抛出ArgumentNullException
):This is what you SEEM to be trying to do, but your example makes it difficult to tell. So, from your comments in other answers it looks like you want to add, subtract, multiply, divide Rational numbers, which means the result should be a Rational as well (not an int).
Thus, you could define each of your methods, then implement operators to call those. The operators are always static, thus you'd need to check for
null
and handle as appropriate (in this case, I'll just throwArgumentNullException
):简单的。只需调用 Add 方法:
Simple. Just call the Add method:
C Sharp - 第 18 课:重载运算符
C Sharp - Lesson 18: Overloading Operators
我不认为你可以重载 int 的 + 运算符!您必须创建自己的包装类或结构:
然后您可以自由地使用“+”做任何您想做的事情。
隐式运算符自动将 int 转换为 MyInt。因此,您可以这样分配:
MyInt x = 7;
显式运算符将 MyInt 转换为 int,如下所示:
int i = (int)x;
其中 x 是 MyInt。I don't think you can overload the + operator for int's! You would have to create your own wrapper class or struct instead:
Then you are free to do with '+' what ever you want to do with it.
The implicit operator automatically converts int's to MyInt. So you could assign like this:
MyInt x = 7;
The explicit operator converts MyInt's to int's like:
int i = (int)x;
where x is a MyInt.