c#进阶-methods中3explicit和implicit
2010-12-26 10:14 撞破南墙 阅读(447) 评论(0) 编辑 收藏 举报为类型添加隐式转换和显示转换
public sealed class Rational {
// Constructs a Rational from an Int32
public Rational(Int32 num) {
}
// Constructs a Rational from a Single
public Rational(Single num) {
}
// Convert a Rational to an Int32
public Int32 ToInt32() {
return 1;
}
// Convert a Rational to a Single
public Single ToSingle() {
return new Single();
}
// Implicitly constructs and returns a Rational from an Int32
public static implicit operator Rational(Int32 num) {
return new Rational(num);
}
// Implicitly constructs and returns a Rational from a Single
public static implicit operator Rational(Single num) {
return new Rational(num);
}
// Explicitly returns an Int32 from a Rational
public static explicit operator Int32(Rational r) {
return r.ToInt32();
}
// Explicitly returns a Single from a Rational
public static explicit operator Single(Rational r) {
return r.ToSingle();
}
}
// Constructs a Rational from an Int32
public Rational(Int32 num) {
}
// Constructs a Rational from a Single
public Rational(Single num) {
}
// Convert a Rational to an Int32
public Int32 ToInt32() {
return 1;
}
// Convert a Rational to a Single
public Single ToSingle() {
return new Single();
}
// Implicitly constructs and returns a Rational from an Int32
public static implicit operator Rational(Int32 num) {
return new Rational(num);
}
// Implicitly constructs and returns a Rational from a Single
public static implicit operator Rational(Single num) {
return new Rational(num);
}
// Explicitly returns an Int32 from a Rational
public static explicit operator Int32(Rational r) {
return r.ToInt32();
}
// Explicitly returns a Single from a Rational
public static explicit operator Single(Rational r) {
return r.ToSingle();
}
}
使用
//隐式转换
Rational r1 = 5; // Implicit cast from Int32 to Rational
Rational r2 = 2.5F; // Implicit cast from Single to Rational
//显示转换
Int32 x = (Int32)r1; // Explicit cast from Rational to Int32
Single s = (Single)r2; // Explicit cast from Rational to Single
Rational r1 = 5; // Implicit cast from Int32 to Rational
Rational r2 = 2.5F; // Implicit cast from Single to Rational
//显示转换
Int32 x = (Int32)r1; // Explicit cast from Rational to Int32
Single s = (Single)r2; // Explicit cast from Rational to Single
实际调用
public static Rational op_Implicit(Int32 num)
public static Rational op_Implicit(Single num)
public static Int32 op_Explicit(Rational r)
public static Single op_Explicit(Rational r)
在实际项目中,为了代码易懂,可能并不常用。但是确实为了某些情况下能看懂别人的代码,知道别人不知道的,才算进阶吧。:)
扩展阅读
作者:撞破南墙
出处:http://www.cnblogs.com/facingwaller/
关于作者:本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。