我试图根据传入的对象类型(在这种情况下为实体)返回一个整数参数,但不确定格式。有什么帮助吗?
entity.ID = db.Create(
entity.Name,
entity.Description,
entity.InitialStep != null ? (int?)entity.InitialStep.ID : null,
entity.IsPrivate,
entity.AllowOnBehalfSubmission,
new Func<int>{something needs to happen here and return an integer});
答案 0 :(得分:0)
您可以通过多种方法指定返回int的函数:
1)指定现有方法
private int MethodReturningInt() { return 1; }
db.Create( /* ... */
MethodReturningInt); // note: no () !
2)使用委托(匿名方法)
db.Create( /* ... */
delegate() { return 1; });
3)使用lambda表达式
db.Create(/* ... */
() => 1);
现在您仍然需要根据需要调整返回值(1)...
答案 1 :(得分:0)
您尝试调用的lambda函数需要在与定义相同的上下文中执行。根据我的理解,你的对象(实体)可以有几种类型,你想根据对象类型设置一个参数值?如果是这样,请按以下行修改代码:
entity.ID = db.Create(
entity.Name,
entity.Description,
entity.InitialStep != null ? (int?)entity.InitialStep.ID : null,
entity.IsPrivate,
entity.AllowOnBehalfSubmission,
new Func<Type, int?> (type =>
{
if (type == typeof(SomeType))
return 1;
if (type == typeof(AnotherType))
return 2;
return null;
})(entity.GetType())
);