CLR via C#学习笔记:C#转换操作符号学习


 

废话少说,看程序就明白了。

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
    
/// <summary>
    
/// C#转换操作符号学习
    
/// </summary>

    public sealed class MyCls
    
{
        
private string _data;

        
public string Data
        
{
            
get return _data; }
            
set { _data = value; }
        }


        
public MyCls(int intValue)
        
{
            _data 
= intValue.ToString();
        }


        
public MyCls(float singleValue)
        
{
            _data 
= singleValue.ToString();
        }


        
public int ToInt32()
        
{
            
int returnValue = -1;
            
if (Int32.TryParse(_data, out returnValue))
            
{
                
return returnValue;
            }

            
else
            
{
                
return -1;
            }

            
        }


        
public float ToSingle()
        
{
            
float returnValue = float.NaN;
            
if (float.TryParse(_data, out returnValue))
            
{
                
return returnValue;
            }

            
else
            
{
                
return float.NaN;
            }


        }


        
隐式转换到基元类型

        
显式从基元转换到Mycls类型
    }


    
class Program
    
{
        
static void Main(string[] args)
        
{
            
//不使用类型转换操作符
            MyCls a = new MyCls(1);
            
int i = a.ToInt32();
            MyCls b 
= new MyCls(float.MinValue);
            
float f = b.ToSingle();

            
//使用类型转换操作符
            MyCls c = (MyCls)i;
            MyCls d 
= (MyCls)f;
            
int k = c;
            
float t = d;
        }

    }

}


 

可研究.NET的Decimal类型,很有学习价值。

原文地址:https://www.cnblogs.com/rockniu/p/1210292.html