简体   繁体   English

哪里重载除法返回自定义类C#operator /(int,int)

[英]Where to overload division returning custom class C# operator/ (int,int)

I'm trying to do this: 我正在尝试这样做:

/// <summary>
/// Syntax support for assigning a new Rational from "x/y" notation.
/// </summary>
/// <param name="num">Numerator, appears before the '/'</param>
/// <param name="denom">Denominator, appears after the '/'</param>
/// <returns>A new Rational using the num/denom convention</returns>
public static Rational operator/(int num,int denom)
{
    Rational r;
    try
    {
        r = new Rational(num, denom);
    }
    catch (Exception e)
    {

        throw e;
    }
    return r;
}

however I get an error when I include it as part of my class, because one of the arguements must be the containing class. 但是当我将它作为我的课程的一部分包含在内时,我会收到错误,因为其中一个争论必须是包含类。 I did notice that this works just fine if I declare it outside main() in my test program, however I would like the class file to contain everything so I can hand off the .cs file. 我确实注意到,如果我在我的测试程序中将它声明在main()之外,这可以正常工作,但我希望类文件包含所有内容,以便我可以将.cs文件移交。 Whats the correct way to do this? 这是正确的方法吗?

Ive also tried 我也试过了

Class Rational
{
     ....
}
public static Rational operator/(...)
{
    ...
}

This does not work because the compiler expects interface,delegate, ... blah blah intellisense keywords. 这不起作用,因为编译器需要interface,delegate,... blah blah intellisense关键字。

Thanks for the help! 谢谢您的帮助!

There is no way to do that. 没有办法做到这一点。 A requirement of a binary operator overload is that one of operands be the type you declaring the operator for. 二元运算符重载的要求是其中一个操作数是您声明运算符的类型。 You can't declare operators for other types. 您不能为其他类型声明运算符。 The operator you are trying to declare is really for int when you think about it, which already has a division operator. 当你考虑它时,你试图声明的运算符实际上是int ,它已经有一个除法运算符。

¶ 7.3.2: ¶7.3.2:

User-defined operator declarations always require at least one of the parameters to be of the class or struct type that contains the operator declaration. 用户定义的运算符声明始终要求至少有一个参数属于包含运算符声明的类或结构类型。 Thus, it is not possible for a user-defined operator to have the same signature as a predefined operator. 因此,用户定义的运算符不可能具有与预定义运算符相同的签名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM