捕获变量实例化问题

捕获变量实例化问题

本文介绍了捕获变量实例化问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在想一些我做错了的主意.

I'm currently musing about some idea I can't get right.

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

The problem is that I want to use one lambda function to instantiate a captured variable and another lambda to access a property of that variable.

由于实例化发生在lambda中,因此该变量实际上并没有在我要在第二个lambda中使用它的时间实例化.

Since the instantiating happens within the lambda the variable isn't actually instantiated the time I want to use it within the second lambda.. this is kind of a chicken and egg problem.

我知道变量将在第二个lambda中被实例化的时间被实例化,但是编译器没有实例化.

I know that the variable will be instantiated the time it's used in the second lambda but the compiler doesn't.

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

Is there any way my idea could work? Here's the actual code:

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();
        }
    }
}

推荐答案

您的意思是仅添加:

SqlCommand cmd = null;

(它解决了确定分配"故障;它明确分配了 ... null ;-p然后在使用该值之前对其进行更新).

(which solves the "definite assignment" glitch; it is definitely assigned... a null ;-p We then update the value before it is used).

IMO,但是,使用嵌套的 using 语句会更好......(从代码中还不清楚)实际的连接来自何处...

IMO, though, you'd do better with nested using statements... and it isn't clear (from the code) where the actual connection is going to come from...

using(var conn = new SqlConnection(...))
using(var cmd = conn.CreateCommand()) {
    // ...
}

这篇关于捕获变量实例化问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 19:39