暗黙的な変換
public static implicit operator 変換後の型(変換元の型 値1) {
return 値2;
}
明示的な変換
public static explicit operator 変換後の型(変換元の型 値1) {
return 値2;
}
明示的な変換の場合は、キャストが指定された時だけ行われる。
暗黙的な変換の例
using System;
class ThreeD {
int x, y, z;
public ThreeD(int i, int j, int k) { x = i; y = j; z = k; }
public static implicit operator double(ThreeD op1) {
return Math.Sqrt(op1.x * op1.x + op1.y * op1.y + op1.z * op1.z);
}
}
class ConversionOpDemo {
static void Main() {
ThreeD alpha = new ThreeD (12, 3, 4);
ThreeD beta = new ThreeD (10, 10, 10);
double dist;
dist = alpha;
Console.Write ("Here is dist: " + dist);
Console.WriteLine ();
if (beta > dist) {
Console.WriteLine ("beta is farther from the origin.");
}
}
}
明示的な変換の例
using System;
class ThreeD {
int x, y, z;
public ThreeD(int i, int j, int k) { x = i; y = j; z = k; }
public static explicit operator double(ThreeD op1) {
return Math.Sqrt(op1.x * op1.x + op1.y * op1.y + op1.z * op1.z);
}
}
class ConversionOpDemo {
static void Main() {
ThreeD alpha = new ThreeD (12, 3, 4);
ThreeD beta = new ThreeD (10, 10, 10);
double dist;
dist = (double)alpha;
Console.Write ("Here is dist: " + dist);
Console.WriteLine ();
if ((double)beta > dist) {
Console.WriteLine ("beta is farther from the origin.");
}
}
}