LoginSignup
1
1

More than 5 years have passed since last update.

変換演算子

Posted at
暗黙的な変換
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.");
        }
    }
}
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1