操作委托可以指向具有返回类型的方法吗? 例如
class Media extends React.Component {
constructor(props) {
super(props);
/*
* Default state.
* We can set the default state based on given props.
*/
let hasMedia = false;
if (props.value) {
hasMedia = !!props.value.id;
}
this.state = {
hasMedia: hasMedia,
media: {
id: props.value ? props.value.id : '',
url: props.value ? props.value.url : '',
name: props.value ? props.value.name : ''
},
};
/*
* Bindings.
*/
this.addImage = this.addImage.bind(this);
this.removeImage = this.removeImage.bind(this);
this.select = this.select.bind(this);
}
componentDidMount(){
/*
* Get a WordPress media frame.
*/
this.wpframe = wp.media({
// Define behaviour of the media window.
// 'post' if related to a WordPress post.
// 'select' if use outside WordPress post.
frame: 'select',
// Allow or not multiple selection.
multiple: false,
// The displayed title.
title: 'Insérer Media',
// The button behaviour
button: {
text: 'Insérer',
close: true
},
// Type of files shown in the library.
// 'image', 'application' (pdf, doc,...)
/*library:{
type: props.type ? props.type : 'image'
}*/
});
// Attach an event on select. Runs when "insert" button is clicked.
this.wpframe.on('select', this.select);
}
以上代码编译。现在,如果我写上面的内容,如
Action a = () => Add();
int Add()
{
return 5 + 6;
}
这不编译。谁能帮助我理解这背后的逻辑呢?
答案 0 :(得分:5)
Action a = () => Add();
int Add()
{
return 5 + 6;
}
在功能上等同于
Action a = ExecuteAdd;
int Add()
{
return 5 + 6;
}
void ExecuteAdd()
{
Add();
}
Action a = new Action(ExecuteAdd);
会编译。
原因是() => Add();
实际上创建了anonymous method。将其分配给Action
类型的变量会推断返回类型void
。
答案 1 :(得分:0)
第一个示例创建一个调用Add
的匿名方法。
Action a = () => Add();
^
Anonymous method with void return type.
如果要将方法分配给Action
,您应该这样做:
Action a = Add;