为类型添加隐式转换和显示转换

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(); 
    } 
}

 

 使用

//隐式转换 
       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)

 

 在实际项目中,为了代码易懂,可能并不常用。但是确实为了某些情况下能看懂别人的代码,知道别人不知道的,才算进阶吧。:)

 扩展阅读 

1参考explicit 和 implicit 的含义?

相关文章:

  • 2021-12-20
  • 2021-12-14
  • 2021-09-28
  • 2022-01-22
  • 2021-12-21
  • 2022-12-23
猜你喜欢
  • 2021-07-25
  • 2021-06-28
  • 2021-10-25
  • 2021-07-31
  • 2021-09-10
相关资源
相似解决方案