捕获变量实例化问题

VVS*_*VVS 1 c# lambda captured-variable

我目前正在思考一些我无法做对的想法.

问题是我想使用一个lambda函数来实例化捕获的变量,并使用另一个lambda来访问该变量的属性.

由于实例化发生在lambda中,变量实际上并没有在我想要在第二个lambda中使用它时实例化.这是一种鸡和蛋的问题.

我知道变量在第二个lambda中使用时实例化,但编译器却没有.

我的想法有什么办法可行吗?这是实际的代码:

class Program
{
    static void Main(string[] args)
    {
        SqlCommand cmd;

        using (new DisposableComposite(
            () => cmd = new SqlCommand(),
            () => cmd.Connection)) // <- compiler error - variable not instantiated
        {
            // code
        }
    }
}

class DisposableComposite : IDisposable
{
    private List<IDisposable> _disposables = new List<IDisposable>();

    public DisposableComposite(params Func<IDisposable>[] disposableFuncs)
    {
        // ensure the code is actually executed
        foreach (var func in disposableFuncs)
        {
            IDisposable obj = func.Invoke();
            _disposables.Add(obj);
        }
    }

    public void Dispose()
    {
        foreach (var disposable in _disposables)
        {
            disposable.Dispose();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 5

你的意思是只是添加:

SqlCommand cmd = null;
Run Code Online (Sandbox Code Playgroud)

(解决了"明确赋值"毛刺;它明确赋值......空在使用前;-p我们再更新值).

但是,IMO对嵌套using语句做得更好......并且(从代码中)不清楚实际连接将来自哪里......

using(var conn = new SqlConnection(...))
using(var cmd = conn.CreateCommand()) {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

  • 该死的......这很简单.我想我需要另一杯咖啡.:) (2认同)