码迷,mamicode.com
首页 > Windows程序 > 详细

C#如何定义与类或结构之间的转换的代码

时间:2020-06-12 12:46:30      阅读:67      评论:0      收藏:0      [点我收藏+]

标签:xpl   ted   stat   not   sys   代码   bsp   operator   roman   

下边资料是关于C#如何定义与类或结构之间的转换的代码。

 


using System;

struct RomanNumeral
{
public RomanNumeral(int value)
{
this.value = value;
}
static public implicit operator RomanNumeral(int value)
{
return new RomanNumeral(value);
}
static public explicit operator int(RomanNumeral roman)
{
return roman.value;
}
static public implicit operator string(RomanNumeral roman)
{
return("Conversion not yet implemented");
}
private int value;
}

class Test
{
static public void Main()
{
RomanNumeral numeral;

numeral = 10;

Console.WriteLine((int)numeral);

Console.WriteLine(numeral);

short s = (short)numeral;

Console.WriteLine(s);
}
}

 

 







using System;

struct RomanNumeral
{
public RomanNumeral(int value)
{
this.value = value;
}
static public implicit operator RomanNumeral(int value)
{
return new RomanNumeral(value);
}
static public implicit operator RomanNumeral(BinaryNumeral binary)
{
return new RomanNumeral((int)binary);
}
static public explicit operator int(RomanNumeral roman)
{
return roman.value;
}
static public implicit operator string(RomanNumeral roman)
{
return("Conversion not yet implemented");
}
private int value;
}

struct BinaryNumeral
{
public BinaryNumeral(int value)
{
this.value = value;
}
static public implicit operator BinaryNumeral(int value)
{
return new BinaryNumeral(value);
}
static public implicit operator string(BinaryNumeral binary)
{
return("Conversion not yet implemented");
}
static public explicit operator int(BinaryNumeral binary)
{
return(binary.value);
}

private int value;
}

class Test
{
static public void Main()
{
RomanNumeral roman;
roman = 10;
BinaryNumeral binary;
binary = (BinaryNumeral)(int)roman;
roman = binary;
Console.WriteLine((int)binary);
Console.WriteLine(binary);
}
}




 

C#如何定义与类或结构之间的转换的代码

标签:xpl   ted   stat   not   sys   代码   bsp   operator   roman   

原文地址:https://www.cnblogs.com/whoamboys/p/13098511.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!