在c#中定义新的算术运算
本文关键字:算术运算 定义 | 更新日期: 2023-09-27 18:16:56
假设我已经创建了一个简单的类
class Zoo {
public int lionCount;
public int cheetahCount;
Zoo(lions, cheetahs) {
lionCount = lions;
cheetahCount = cheetahs;
}
}
现在假设我有两个动物园。
Zoo zoo1 = new Zoo(1,2);
Zoo zoo2 = new Zoo(3,5);
是否可以为这个类定义算术运算,使…
Zoo zoo3 = zoo1 + zoo2; //makes a zoo with 4 lions and 7 cheetahs
Zoo zoo4 = zoo1 * zoo2; // makes a zoo with 3 lions and 10 cheetahs
换句话说,我如何为c#类定义自定义算术运算?
当然可以使用操作符重载
class Zoo
{
public int lionCount;
public int cheetahCount;
Zoo(int lions, int cheetahs)
{
lionCount = lions;
cheetahCount = cheetahs;
}
public static Zoo operator +(Zoo z1, Zoo z2)
{
return new Zoo(z1.lionCount + z2.lionCount, z1.cheetahCount + z2.cheetahCount);
}
}
其他操作符的处理方式基本相同;-)
更多信息请查看https://msdn.microsoft.com/en-us/library/aa288467(v=vs.71).aspx
操作符重载可以这样完成:
public static Zoo operator +(Zoo z1, Zoo z2)
{
return new Zoo(z1.lionCount + z2.lionCount, z1.cheetahCount + z2.cheetahCount);
}
我想你可以自己算出其他运算符。有关更多信息,请参阅本教程:链接到教程
注意:操作符必须放在类本身中(本例中为Zoo
类)