2つのクラスがあると考えてください。
internal class Explicit
{
public static explicit operator int (Explicit a)
{
return 5;
}
}
internal class Implicit
{
public static implicit operator int(Implicit a)
{
return 5;
}
}
および2つのオブジェクト:
var obj1 = new Explicit();
var obj2 = new Implicit();
あなたは今書くことができます:
int integer = obj2; // implicit conversion - you don't have to use (int)
また:
int integer = (int)obj1; // explicit conversion
しかし:
int integer = obj1; // WON'T WORK - explicit cast required
暗黙的な変換は、変換の精度が低下しない場合に使用することを目的としています。明示的な変換とは、ある程度の精度を失う可能性があり、自分が何をしているかを知っていることを明確に述べなければならないことを意味します。
暗黙的/明示的な用語が適用される2番目のコンテキスト(インターフェイスの実装)もあります。その場合、キーワードはありません。
internal interface ITest
{
void Foo();
}
class Implicit : ITest
{
public void Foo()
{
throw new NotImplementedException();
}
}
class Explicit : ITest
{
void ITest.Foo() // note there's no public keyword!
{
throw new NotImplementedException();
}
}
Implicit imp = new Implicit();
imp.Foo();
Explicit exp = new Explicit();
// exp.Foo(); // won't work - Foo is not visible
ITest interf = exp;
interf.Foo(); // will work
したがって、明示的なインターフェイス実装を使用する場合、具象型を使用するとインターフェイスのメソッドは表示されません。これは、インターフェースがヘルパーインターフェースであり、クラスの主要な責任の一部ではなく、コードを使用して誰かを誤解させるような追加のメソッドが必要ない場合に使用できます。