C# “什么是”呢;“接口的结构类型”;打字
马克·伦德尔(Mark Rendle)在《关于打字稿》中说,他喜欢它的一个方面是: “接口的结构类型。我真希望C#能做到这一点”C# “什么是”呢;“接口的结构类型”;打字,c#,typescript,structural-typing,C#,Typescript,Structural Typing,马克·伦德尔(Mark Rendle)在《关于打字稿》中说,他喜欢它的一个方面是: “接口的结构类型。我真希望C#能做到这一点” 他这是什么意思?基本上,这意味着在“duck类型”的基础上比较接口,而不是在类型标识的基础上比较接口 考虑以下C#代码: 和等效的TypeScript代码: interface X1 { name: string; } interface X2 { name: string; } var a: X1 = null; var b: X2 = a; // OK: X1 a
他这是什么意思?基本上,这意味着在“duck类型”的基础上比较接口,而不是在类型标识的基础上比较接口 考虑以下C#代码: 和等效的TypeScript代码:
interface X1 { name: string; }
interface X2 { name: string; }
var a: X1 = null;
var b: X2 = a; // OK: X1 and X2 have the same members, so they are compatible
规范没有详细介绍这一点,但类有“品牌”,这意味着使用类而不是接口编写的相同代码将有错误。C#接口确实有品牌,因此不能隐式转换
考虑这个问题最简单的方法是,如果您尝试从接口X转换到接口Y,如果X拥有Y的所有成员,则转换成功,即使X和Y可能没有相同的名称。想想看
class Employee { fire: = ..., otherMethod: = ...}
class Missile { fire: = ..., yetMoreMethod: = ...}
interface ICanFire { fire: = ...}
val e = new Employee
val m = new Missile
ICanFire bigGuy = if(util.Random.nextBoolean) e else m
bigGuy.fire
如果我们说:
interface IButtonEvent { fire: = ...}
interface IMouseButtonEvent { fire: = ...}
...
TypeScript将允许这样做,而C#将不允许
由于TypeScript旨在与使用“松散”类型的DOM很好地协同工作,因此它是TypeScript唯一明智的选择
我把它留给读者来决定他们是否喜欢“结构类型” 我已经简单地阅读了这篇文章,对它做了一点澄清,但我仍然想知道它是如何在TypeScript中使用的
interface IButtonEvent { fire: = ...}
interface IMouseButtonEvent { fire: = ...}
...