11
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C# VB.NET における暗黙型変換の実装

Last updated at Posted at 2014-04-15

Scalaではおなじみの暗黙変換(implicit conversion)だが、C#/VB.NETにも同等の機能があります。

以下、リファレンスより抜粋。

class Digit
{
    public Digit(double d) { val = d; }
    public double val;
    // ...other members

    // User-defined conversion from Digit to double
    public static implicit operator double(Digit d)
    {
        return d.val;
    }
    //  User-defined conversion from double to Digit
    public static implicit operator Digit(double d)
    {
        return new Digit(d);
    }
}

これでdouble num = new Digit(1);というような等式が使えるようになる。
なお、暗黙ではなく明示的((hogeClass)variable というような変換)である、という場合はexplicitを使う(リファレンス参照)。

さて、VB.NETでは暗黙変換の演算子はWideningNarrowingで区別される。

以下、リファレンスのコード。

Public Structure digit
  Private dig As Byte
  Public Sub New(ByVal b As Byte)
    If (b < 0 OrElse b > 9) Then Throw New System.ArgumentException("Argument outside range for Byte")
      Me.dig = b
  End Sub

  Public Shared Widening Operator CType(ByVal d As digit) As Byte
      Return d.dig
  End Operator
  Public Shared Narrowing Operator CType(ByVal b As Byte) As digit
      Return New digit(b)
  End Operator
End Structure

Single から Doubleのように精度が落ちず普通に変換できる場合はWidening、逆にLong から Integerなど精度が落ちる場合はNarrowingとなり、それぞれに応じた処理を実装できる(特に精度が落ちる場合は使い出があるかも)。これと等価な機能はC#にはない・・・ように見える(Narrowingがexplicitに該当する?)。

11
11
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
11
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?