【问题标题】:Is it possible to access variable in a labda expression? c#是否可以访问 lambda 表达式中的变量? C#
【发布时间】: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 类。

标签: c# lambda scope


【解决方案1】:

我不明白,你到底想要什么。

但如果你打电话:

 return Do<string>(() => { });

() =&gt; {} 表示带有 lamda 表达式的函数。但是该函数独立于您的类型声明。在您的类型声明中,您有一个函数作为参数,但此函数与您的类型无关。

我认为,这就是为什么您无法访问“co”的原因。

更新:

这对你来说是一个解决方案吗?

 public static class Get
{
    public static class Question
    {
        public static string byId()
        {
            Func<OracleConnection, string> func1 = (co) => co.ToString();


            return Do<string>(func1);
        }
    }
}

 public static type Do<type>(Func<OracleConnection, type> fun)
    {
        OracleConnection co = null;
        type ret = default(type);
        try
        {
            co = CreateCo();
            MessageBox.Show("Connected");
            ret = fun(co);
        }
        catch (Exception)
        {
            MessageBox.Show("Error");
        }
        finally
        {
            CloseCo(co);
        }
        return ret;
    }

【讨论】:

  • 有道理,我想做的是在“Do”函数中执行一段代码,并且在这段代码中能够访问“Do”范围内的变量。
  • 我明白你想要什么。我已经更新了我的答案。希望对你有帮助。
  • 简直太棒了,非常感谢,它真的很好用。
猜你喜欢
  • 1970-01-01
  • 2017-04-19
  • 2014-09-12
  • 2014-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-03
  • 2011-03-19
相关资源
最近更新 更多