【发布时间】:2017-04-18 22:28:32
【问题描述】:
我希望能够在我的 lambda 表达式中访问“co”。有可能这样做吗?如果是的话怎么办?如果没有,我应该怎么做?
我想在我的函数“Do”中传递一段代码,我可以在其中使用“Do”范围内的变量。
如果你不知道我在说什么,请问我任何问题,我会尽力解释得更好。
public static type Do<type>(Func<type> fun)
{
OracleConnection co = null;
type ret = default(type);
try
{
co = CreateCo();
MessageBox.Show("Connected");
ret = fun();
}
catch (Exception)
{
MessageBox.Show("Error");
}
finally
{
CloseCo(co);
}
return ret;
}
public static class Get
{
public static class Question
{
public static string byId()
{
//This lambda expression
return Do<string>(() =>
{ co./*here I can't access my object: why? how? */ });
}
}
}
当我得到答案时,我会用答案更新这篇文章: ->One answer that work !!!
【问题讨论】:
-
co在另一个类中声明(至少从您的代码看起来是这样)。您需要将其设为当前声明的类的公共属性,然后从其他类访问它,或者通过构造函数或方法调用将其传递给Get类。