我有两个接口:
public interface IAmA
{
}
public interface IAmB<T> where T : IAmA
{
}
Run Code Online (Sandbox Code Playgroud)
实现这些接口的两个类如下:
public class ClassA : IAmA
{
}
public class ClassB : IAmB<ClassA>
{
}
Run Code Online (Sandbox Code Playgroud)
尝试使用这些类时如下所示:
public class Foo
{
public void Bar()
{
var list = new List<IAmB<IAmA>>();
list.Add(new ClassB());
}
}
Run Code Online (Sandbox Code Playgroud)
我得到这个编译器错误:
cannot convert from 'ClassB' to 'IAmB<IAmA>'
我知道我可以使编译器使用:
public class ClassB : IAmB<IAmA>
{
}
Run Code Online (Sandbox Code Playgroud)
不过,我需要能够成为该类型参数IAmB<>中ClassB的一个实现IAmA.
这段代码:
'use strict'
function Ob() {}
Ob.prototype.add = () => {
this.inc()
}
Ob.prototype.inc = () => {
console.log(' Inc called ');
}
module.exports = new Ob();
Run Code Online (Sandbox Code Playgroud)
由此代码使用:
'use strict'
const ob = require('./ob')
ob.add();
Run Code Online (Sandbox Code Playgroud)
调用梯形图时,我收到此错误:
this.inc is not a function
当我将第一个代码段更改为:
'use strict'
function Ob() {}
Ob.prototype.add = function() {
this.inc();
}
Ob.prototype.inc = function() {
console.log(' Inc called ');
}
module.exports = new Ob();
Run Code Online (Sandbox Code Playgroud)
一切都很好,我得到:
Inc called
为什么第一个版本会抛出?
更新:如何使用箭头功能使其工作?