【发布时间】:2013-02-24 09:24:21
【问题描述】:
任何人都可以解释以下程序,用户定义转换是如何显式和隐式发生的?
在显式转换方法和隐式转换方法上也请看我的cmets。
/*** conversion.cs ***/
using System;
using System;
struct RomanNumeral {
public RomanNumeral(int value) {
this.value=value; // what happen here??
}
static public implicit operator RomanNumeral(int value) {
// here the default constructor is called and the parameter in the
// argument is passed for the conversion to RomanNumeral but the
// constructor is of the type int so how it happen please explain??
return new RomanNumeral(value);
}
static public explicit operator int(RomanNumeral roman) {
return roman.value;//how it is happen here??
}
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);
}
}
【问题讨论】:
-
完全不清楚您所说的“这里是如何发生的”是什么意思。
-
@jon keet 我的意思是它如何访问值 int 构造函数??
-
为什么不能调用构造函数?它在同一个类中声明。 (无论如何,它是一个公共构造函数。)
标签: c# casting operators implicit-conversion explicit-conversion