转载注明出处:连接1: 点击打开链接 连接2:点击打开链接
operator
operator 关键字用于在类或结构声明中声明运算符。运算符声明可以采用下列四种形式之一:
-
public static result-type operator unary-operator ( op-type operand )
-
public static result-type operator binary-operator ( op-type operand, op-type2 operand2 )
-
public static implicit operator conv-type-out ( conv-type-in operand )
-
public static explicit operator conv-type-out ( conv-type-in operand )
参数:
- result-type 运算符的结果类型。
- unary-operator 下列运算符之一:+ - ! ~ ++ — true false
- op-type 第一个(或唯一一个)参数的类型。
- operand 第一个(或唯一一个)参数的名称。
- binary-operator 其中一个:+ - * / % & | ^ << >> == != > < >= <=
- op-type2 第二个参数的类型。
- operand2 第二个参数的名称。
- conv-type-out 类型转换运算符的目标类型。
- conv-type-in 类型转换运算符的输入类型。
implicit 关键字用于声明隐式的用户定义类型转换运算符。如果可以确保转换过程不会造成数据丢失,则可使用该关键字在用户定义类型和其他类型之间进行隐式转换。隐式转换可以通过消除不必要的类型转换来提高源代码的可读性。但是,因为隐式转换不需要程序员将一种类型显式强制转换为另一种类型,所以使用隐式转换时必须格外小心,以免出现意外结果。
explicit 关键字用于声明必须使用强制转换来调用的用户定义的类型转换运算符。转换运算符将源类型转换为目标类型。源类型提供转换运算符。与隐式转换不同,必须通过强制转换的方式来调用显式转换运算符。如果转换操作可能导致异常或丢失信息,则应将其标记为explicit。这可以防止编译器无提示地调用可能产生无法预见后果的转换操作。例如,在下面的示例中,此运算符将名为 Fahrenheit 的类转换为名为 Celsius 的类:
public class Fahrenheit
{
private float degrees;
public float Degrees
{
get { return degrees; }
set { degrees = value; }
}
public Fahrenheit(float _degrees)
{
this.degrees = _degrees;
}
//也可以将以下运算符重载方法写在Celsius类中,但是只能编写一次,否则将造成编译错误。
public static explicit operator Celsius(Fahrenheit f)
{
return new Celsius((5.0f / 9.0f) * (f.Degrees - 32));
}
public static explicit operator Fahrenheit(Celsius c)
{
return new Fahrenheit(c.Degrees * (9.0f / 5.0f) + 32);
}
}
public class Celsius
{
private float degrees;
public float Degrees
{
get { return degrees; }
set { degrees = value; }
}
public Celsius(float _degrees)
{
this.degrees = _degrees;
}
//public static explicit operator Celsius(Fahrenheit f)
//{
// return new Celsius((5.0f / 9.0f) * (f.Degrees - 32));
//}
//public static explicit operator Fahrenheit(Celsius c)
//{
// return new Fahrenheit(c.Degrees * (9.0f / 5.0f) + 32);
//}
}
public class Digit
{
public Digit(double d) { val = d; }
public double val;
// ...other members
// User-defined conversion from Digit to double
public static implicit operator double(Digit d)
{
return d.val;
}
// User-defined conversion from double to Digit
public static implicit operator Digit(double d)
{
return new Digit(d);
}
}
static void Main()
{
//以下示例演示使用implicit关键字用于声明隐式的用户定义类型转换运算符
//Digit dig = new Digit(7);
////This call invokes the implicit "double" operator
//double num = dig;
////This call invokes the implicit "Digit" operator
//Digit dig2 = 12;//隐式转换
//Console.WriteLine("num = {0} dig2 = {1}", num, dig2.val);
//Console.ReadLine();
//以下示例演示使用explicit关键字用于声明必须使用强制转换来调用的用户定义的类型装换运算符
Fahrenheit f = new Fahrenheit(100.0f);
Celsius c = (Celsius)f;
//Console.Write("{0} celsius", c.Degrees);
Celsius cc = new Celsius(37.7f);
Fahrenheit ff = (Fahrenheit)cc;//必须强制转换
Console.Write("{0} Fahrenheit", ff.Degrees);
}