Tag: 运算符重载

需要重载operator <和null检查

我在c#中重载了lessthan-operator,我想知道这是否需要检查null。 您可以在下面找到一个示例: public static bool operator <(MyClass x, MyClass y) { if (x == null && y == null) { return false; } if (x == null) { return true; //false? } if (y == null) { return false; //true? } return x.Value < y.Value; } 或者这是正确的: public static bool operator <(MyClass x, MyClass y) […]

运算符重载与generics

可能重复: C#中generics类的算术运算符重载 这是我创建的generics类的代码,用于将复数添加到重载运算符。 public class Complex { public T _a, _b; public Complex(T i, T j) { _a = i; _b = j; } public static Complex operator +(Complex i, Complex j) { return new Complex(i._a + j._a, i._b + j._b); } } 在使用这个时,我有一个错误, Error: Operator ‘+’ cannot be applied to operands of type ‘T’ […]

在C#中是否可以通过以下方式重载通用转换运算符?

只是想知道是否还有代表C#3.5中的以下代码: public struct Foo { public Foo(T item) { this.Item = item; } public T Item { get; set; } public static explicit operator Foo ( Foo a ) where U : T { return new Foo((U)a.Item) } } 谢谢

方法超载分辨率和Jon Skeet的Brain Teasers

乔恩的脑筋急转弯 这里是剧透…… 我正在看#1的答案 ,我必须承认我从来不知道重载决议是这种情况。 但为什么会这样呢。 在我的小脑海中, Derived.Foo(int)似乎是合乎逻辑的路线。 这个设计决定背后的逻辑是什么? 奖金时间! 此行为是C#规范,CLR实现还是编译器的结果?

为什么C#运算符重载必须是静态的?

为什么C#要求运算符重载是静态方法而不是成员函数(如C ++)? (也许更具体地说:这个决定的设计动机是什么?)

在C#中重载函数调用操作符

是否可以在C#中重载默认函数运算符(()运算符)? 如果是这样 – 怎么样? 如果没有,是否有解决方法来创建类似的影响? 谢谢, 阿萨夫 编辑: 我试图给一个类一个默认运算符,类似于: class A { A(int myvalue) {/*save value*/} public static int operator() (A a) {return a.val;} …. } … A a = new A(5); Console.Write(A()); 编辑2: 我已经阅读了规范,我知道没有直接的方法来做到这一点。 我希望有一个解决方法。 编辑3:动机是使一个类或一个实例表现得像一个函数,以创建一个方便的日志记录界面。 顺便说一句,这在C ++中是可行和合理的。

在关于Equals覆盖的msdn指南中,为什么在null检查中转换为对象?

我只是在msdn上查看重载等于()的指南 (参见下面的代码); 大部分内容对我来说很清楚,但有一条线我没有得到。 if ((System.Object)p == null) 或者,在第二次覆盖中 if ((object)p == null) 为什么不简单 if (p == null) 什么是反对购买我们的演员? public override bool Equals(System.Object obj) { // If parameter is null return false. if (obj == null) { return false; } // If parameter cannot be cast to Point return false. TwoDPoint p = obj as TwoDPoint; […]

重载+运算符以添加两个数组

这个C#代码有什么问题? 我试图重载+运算符以添加两个数组,但收到如下错误消息: 二元运算符的参数之一必须是包含类型。 class Program { public static void Main(string[] args) { const int n = 5; int[] a = new int[n] { 1, 2, 3, 4, 5 }; int[] b = new int[n] { 5, 4, 3, 2, 1 }; int[] c = new int[n]; // c = Add(a, b); c = a + […]

后增量运算符重载

我在尝试在C#中重载后增量运算符时遇到问题。 使用整数我们得到以下结果。 int n; n = 10; Console.WriteLine(n); // 10 Console.WriteLine(n++); // 10 Console.WriteLine(n); // 11 n = 10; Console.WriteLine(n); // 10 Console.WriteLine(++n); // 11 Console.WriteLine(n); // 11 但是,当我尝试使用类时,它看起来像是交换对象。 class Account { public int Balance { get; set; } public string Name { get; set; } public Account(string name, int balance) { Balance = balance; […]