c# - 如何返回方法 C#

标签 c# operators

我需要在运算符函数中返回一个方法。

        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/

相关文章:

c# - MSDTC 的 WCF Windows 服务问题

scope - Sublime Text : scope selector operators

javascript - 为什么 '+' 运算符要连接我的数字?

c# - 实时磁贴更新的最佳选择

C# 在 "bulk"中设置属性值(通过排除)

c - -14 的左移 2 位是 =-56?如何?

c# - 等价于 C# 中的 `IF ( X AND ( 2 ^ Y ) ) Then`

c - && 优先于 ||

c# - 发布时的 TransformXml Web.config

c# - 显示 Context MenuStrip 或按钮的上下文菜单的复选框