我需要在运算符函数中返回一个方法。
public int Add()
{
return 1;
}
public static int operator +()
{
return Add;
}
我也需要为乘法、减法和除法运算符/函数执行此操作。
谢谢
最佳答案
您不能声明无参数运算符。您可以声明一个运算符以返回适当的委托(delegate) - 例如Func<int>
- 但在我看来,这将是一件很奇怪的事情。
如果您能告诉我们更多关于您想要实现的目标,我们可能会帮助您设计出更简洁的设计。
这是一个非常奇怪的重载一元 + 运算符的例子:
using System;
class Weird
{
private readonly int amount;
public Weird(int amount)
{
this.amount = amount;
}
private int Add(int original)
{
return original + amount;
}
// Very strange. Please don't do this.
public static Func<int, int> operator +(Weird weird)
{
return weird.Add;
}
}
class Test
{
static void Main(string[] args)
{
Weird weird = new Weird(2);
Func<int, int> func = +weird;
Console.WriteLine(func(3));
}
}
编辑:如果您只是想实现一个 Rational
类型,你更有可能想要:
public struct Rational
{
// Other members
public Rational Add(Rational other)
{
...
}
public static Rational operator +(Rational left, Rational right)
{
return left.Add(right);
}
}
关于c# - 如何返回方法 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7998751/