C#中的重载划分 [英] Overload division in C#

查看:35
本文介绍了C#中的重载划分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的C#类中重载除法运算符.所以,我写道:

I want to overload division operator in my C# class. So, i wrote:

public string[] operator/ (object obj) {

}

并得到错误:解析器错误:可重载的一元运算符除外".
所以,我不能重载该运算符吗?
在MSDN上,我没有看到任何示例: http://msdn.microsoft.com/en-us/library/3b1ff23f.aspx
谢谢.

And got error: "Parser error: Overloadable unary operator excepted".
So, i cant overload that operator?
On the MSDN i don't see any example: http://msdn.microsoft.com/en-us/library/3b1ff23f.aspx
Thanks.

///如果需要,我正在Ubuntu 14.10上使用MonoDevelop.

//i'm using MonoDevelop on Ubuntu 14.10, if it's needed.

推荐答案

您可以重载除法运算符,但是:

You can overload the division operator, but:

  • 它必须始终是二进制运算符-您仅提供了一个操作数
  • 它必须始终是静态的
  • 至少一种操作数类型必须是您要在其中声明的类型

例如:

using System;

class Program
{
    public static string operator/ (Program lhs, int rhs)
    {
        return "I'm divided!";
    }

    static void Main(string[] args)
    {
        Console.WriteLine(new Program() / 10);
    }
}

这篇关于C#中的重载划分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆