今天我很惊讶地看到这是可能的,但我担心这必须事先讨论。
public interface ICanAdd
{
int Add(int x, int y);
}
// Note that MyAdder does NOT implement ICanAdd,
// but it does define an Add method like the one in ICanAdd:
public class MyAdder
{
public int Add(int x, int y)
{
return x + y;
}
}
public class Program
{
void Main()
{
var myAdder = new MyAdder();
var iCanAdd = (ICanAdd)myAdder; //compiles, but for what sake?
int sum = iCanAdd.Add(2, 2); //na, not game for it, cast had already failed
}
}
编译器会(对吗?)告诉我在上述情况下存在显式转换。我很高兴能感觉到那里的结构打字,但没有运行时间它失败。那么 C# 什么时候在这里有用呢?这种铸造的任何场景都行得通吗?不管是什么,我确信编译器事先知道myAdder
不是ICanAdd
,从技术上讲。