Era*_*dan 18 c# structural-typing typescript
Mark Rendle 在他关于TypeScript的博客文章中说,他喜欢的一件事是:
"接口的结构类型.我真的希望C#可以做到这一点"
那是什么意思?
Rya*_*ugh 20
基本上,它意味着接口在"鸭子打字"的基础上进行比较,而不是基于类型身份.
考虑以下C#代码:
interface X1 { string Name { get; } }
interface X2 { string Name { get; } }
// ... later
X1 a = null;
X2 b = a; // Compile error! X1 and X2 are not compatible
Run Code Online (Sandbox Code Playgroud)
和等效的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
Run Code Online (Sandbox Code Playgroud)
规范没有详细介绍这一点,但是类有"品牌",这意味着用类而不是接口编写的相同代码会出错.C#接口确实有品牌,因此不能隐式转换.
考虑它的最简单方法是,如果您尝试从接口X转换到接口Y,如果X具有Y的所有成员,则转换成功,即使X和Y可能没有相同的名称.
归档时间: |
|
查看次数: |
1493 次 |
最近记录: |