Overload division in C#

不想你离开。 提交于 2019-12-11 03:54:48

问题


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

public string[] operator/ (object obj) {

}

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.

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


回答1:


You can overload the division operator, but:

  • It must always be a binary operator - you've only provider one operand
  • It must always be static
  • At least one of the operand types must be the type you're declaring it in

So for example:

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);
    }
}



回答2:


The / operator is a "binary" operator, meaning that it takes two arguments: a / b. The way you've written this, it's trying to overload it as a "unary" operator, such as a++.

Something like this ought to work, assuming your class is called "MyObject".

public static string[] operator/ (MyObject mine, object obj) {
    ...
}

Usage:

object something = "hi";
string[] result = new MyObject(1) / something;


来源:https://stackoverflow.com/questions/27625627/overload-division-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!