使用c#,如何一次重载所有运算符?
我有一个这样的结构使用c#,如何一次重载所有运算符?,c#,operator-overloading,conversion-operator,C#,Operator Overloading,Conversion Operator,我有一个这样的结构 public struct Money { private readonly decimal _quantity; private Money(decimal qty) { _quantity = Math.Round(qty, 2); } public static implicit operator Money(decimal dec) { return new Money(dec);
public struct Money
{
private readonly decimal _quantity;
private Money(decimal qty)
{
_quantity = Math.Round(qty, 2);
}
public static implicit operator Money(decimal dec)
{
return new Money(dec);
}
}
对于Money
我是否必须重载所有运算符+,-,=,=,=,!=,等或者有没有一种方法可以同时接受Money
的所有decimal
运算符?如您所见,Money
只有一个字段,即\u quantity
。我希望所有要求付款的运营商都能像要求数量一样返回
也许在隐式转换运算符下面重载可以解决这个问题
public static implicit operator decimal(Money money)
{
return money._quantity;
}
我正在创建Money
struct,因为我不想在整个项目中使用decimal
。编译器应该强制我使用Money
而不是decimal
。如果我隐式地使用上述转换运算符,它将与创建此结构背后的原因相矛盾。
提前感谢…您必须单独实现所有操作符,但您可以简化流程
通过实现静态比较
方法(为了模拟C不支持的
运算符):
public struct Money:i比较{
专用只读十进制数量;
...
//C#没有操作员,唉。。。
公共静态整数比较(左钱,右钱){
if(左数量<右数量)
返回-1;
否则如果(左。\数量>右。\数量)
返回1;
其他的
返回0;
}
公共静态布尔运算符==(左侧货币,右侧货币){
返回比较(左、右)==0;
}
公共静态布尔运算符!=(左钱,右钱){
返回比较(左、右)!=0;
}
公共静态布尔运算符>(左侧货币,右侧货币){
返回比较(左、右)>0;
}
公共静态布尔运算符<(左钱,右钱){
返回比较(左、右)<0;
}
公共静态布尔运算符>=(左侧货币,右侧货币){
返回比较(左、右)>=0;
}
公共静态布尔运算符谢谢你的回答Dmitry。但是我的运算符重载方法已经有了结构return left.\u quantityright.\u quantity
。如果c#支持泛型运算符和泛型类型,那么我的问题就会有答案。@serdar:是的,没有“”运算符(可以组合所有比较)和数字类型(用于实现算术)有时很烦人。
public struct Money: IComparble<Money> {
private readonly decimal _quantity;
...
// C# doesn't have <=> operator, alas...
public static int Compare(Money left, Money right) {
if (left._quantity < right._quantity)
return -1;
else if (left._quantity > right._quantity)
return 1;
else
return 0;
}
public static Boolean operator == (Money left, Money right) {
return Compare(left, right) == 0;
}
public static Boolean operator != (Money left, Money right) {
return Compare(left, right) != 0;
}
public static Boolean operator > (Money left, Money right) {
return Compare(left, right) > 0;
}
public static Boolean operator < (Money left, Money right) {
return Compare(left, right) < 0;
}
public static Boolean operator >= (Money left, Money right) {
return Compare(left, right) >= 0;
}
public static Boolean operator <= (Money left, Money right) {
return Compare(left, right) <= 0;
}
public int CompareTo(Money other) {
return Compare(this, other);
}
}