C# - 为什么我不能将using语句中声明的类作为引用类型传递?

Iri*_*can 17 c#

假设我有以下一次性类和示例代码来运行它:

public class DisposableInt : IDisposable
{
    private int? _Value;

    public int? MyInt
    {
        get { return _Value; }
        set { _Value = value; }
    }

    public DisposableInt(int InitialValue)
    {
        _Value = InitialValue;
    }

    public void Dispose()
    {
        _Value = null;
    }
}

public class TestAnInt
{
    private void AddOne(ref DisposableInt IntVal)
    {
        IntVal.MyInt++;
    }

    public void TestIt()
    {
        DisposableInt TheInt;
        using (TheInt = new DisposableInt(1))
        {
            Console.WriteLine(String.Format("Int Value: {0}", TheInt.MyInt));
            AddOne(ref TheInt);
            Console.WriteLine(String.Format("Int Value + 1: {0}", TheInt.MyInt));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

通话new TestAnInt().TestIt()运行得很好.但是,如果我改变,TestIt()那么DisposableInt在using语句中声明如下:

    public void TestIt()
    {
        // DisposableInt TheInt;
        using (DisposableInt TheInt = new DisposableInt(1))
        {
            Console.WriteLine(String.Format("Int Value: {0}", TheInt.MyInt));
            AddOne(ref TheInt);
            Console.WriteLine(String.Format("Int Value + 1: {0}", TheInt.MyInt));
        }
    }
Run Code Online (Sandbox Code Playgroud)

我得到以下编译器错误:

Cannot pass 'TheInt' as a ref or out argument because it is a 'using variable'
Run Code Online (Sandbox Code Playgroud)

为什么是这样?什么是不同的,除了类超出范围和using语句完成后的垃圾收集器?

(是的,我知道我的一次性课程实例非常愚蠢,我只是想让事情变得简单)

Jon*_*eet 28

为什么是这样?

变量声明using声明只读; outref参数不是.所以你可以这样做:

DisposableInt theInt = new DisposableInt(1);
using (theInt)
{
    AddOne(ref theInt);
}
Run Code Online (Sandbox Code Playgroud)

......但从根本上说,你并没有使用ref无论如何都是一个参数......

你可能误解了ref真正含义的东西.阅读我关于参数传递的文章以确保您真正理解是一个好主意.