我正在尝试构造接受更多一个参数的函数。接受一个参数的Lambda函数工作正常。这是代码。
var value = 22.55;
var method = typeof(TextWriter).GetMethod("WriteLine", new Type[] { value.GetType() });
ParameterExpression inputParameter = Expression.Parameter(typeof(TextWriter));
var block = Expression.Block(
inputParameter,
Expression.Call(inputParameter, method, Expression.Constant(value)));
var function = Expression.Lambda<Action<TextWriter>>(block, inputParameter).Compile();
function(Console.Out);
然而,当我添加一个我甚至不使用的参数时,函数抛出null引用异常。我必须遗漏一些东西,但不知道是什么。以下代码不起作用:
var value = 22.55;
var method = typeof(TextWriter).GetMethod("WriteLine", new Type[] { value.GetType() });
ParameterExpression inputParameter = Expression.Parameter(typeof(TextWriter));
// Additional parameter here
ParameterExpression inputParameter2 = Expression.Parameter(typeof(double));
var block = Expression.Block(
// Function block accepts two parameters
new List<ParameterExpression>() { inputParameter, inputParameter2 },
Expression.Call(inputParameter, method, Expression.Constant(value)));
var function = Expression.Lambda<Action<TextWriter, double>>(block, inputParameter, inputParameter2).Compile();
// ....aaand null exception here. Why?
function(Console.Out, value);
我在这里做错了什么?
答案 0 :(得分:1)
根据您的评论判断,您误解了您传递给 $('button.delete').on('click', function(event){
event.preventDefault();
var form = $(this).closest(".delete-form");
swal({
title: "Are you sure",
text: "Can i delete?",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Sim!",
closeOnConfirm: false
},
function(){
form.submit();
});
})
的内容。 Block的Block
参数用于定义局部变量,而不是参数。
variables
应该只是
var block = Expression.Block(
// Function block accepts two parameters
new List<ParameterExpression>() { inputParameter, inputParameter2 },
Expression.Call(inputParameter, method, Expression.Constant(value)));
您目前正在做的是:
var block = Expression.Block(Expression.Call(inputParameter, method, Expression.Constant(value)));
虽然实际只是想要:
void function(TextWriter tw, double d) {
TextWriter tw = default(TextWriter);
double d = default(double);
tw.WriteLine(22.55);
}
另外,您实际上并没有使用第二个参数。完整的工作代码是:
void function(TextWriter tw, double d) {
tw.WriteLine(22.55);
}
您的第一个代码有效,因为您使用了不同的块重载。您没有为var method = typeof(TextWriter).GetMethod("WriteLine", new Type[] { typeof(double) });
ParameterExpression inputParameter = Expression.Parameter(typeof(TextWriter));
ParameterExpression inputParameter2 = Expression.Parameter(typeof(double));
var block = Expression.Block(Expression.Call(inputParameter, method, inputParameter2));
var function = Expression.Lambda<Action<TextWriter, double>>(block, inputParameter, inputParameter2).Compile();
function(Console.Out, 35.5);
声明局部变量,而是将其作为表达式本身传递。所以,代码看起来像这样:
inputParameter