为什么我不能转换ref参数?

pro*_*ice 4 c#

我有一个带有ref控件类型参数的方法,我想通过传递ref按钮类型参数来调用它.

那么编译器不接受这个,我必须将ref控件类型更改为ref按钮类型.

为什么?

Dan*_*ner 27

因为这会引起很多问题......

public void DoDarkMagic(ref Control control)
{
    control = new TextBox();
}

public void Main()
{
    Button button = new Button();

    DoDarkMagic(ref button);

    // Now your button magically became a text box ...
}
Run Code Online (Sandbox Code Playgroud)


Bri*_*lph 9

你可以用泛型来解决一些打字限制.

void Test<T>(ref T control)
   where T: Control
{
}
Run Code Online (Sandbox Code Playgroud)

现在你可以打电话:

Button b = new Button() 
Test(b);
Run Code Online (Sandbox Code Playgroud)

您可以将任何类型的引用传递给它,该引用来自控件.

现实生活场景:

 protected static void BindCollection<T>(
        T list
        , ref T localVar
        , ref ListChangedEventHandler eh // the event handler
        , ListChangedEventHandler d) //the method to bind the event handler if null
        where T : class, IBindingList
    {
        if (eh == null)
            eh = new ListChangedEventHandler(d);

        if (list != null && list != localVar)
        {
            if (localVar != null)
                localVar.ListChanged -= eh;

            localVar = list;

            list.ListChanged += eh;
        }
        else if (localVar != null && list == null)
        {
            localVar.ListChanged -= eh;
            localVar = list;
        }
    }

public override BindingList<ofWhatever> Children
    {
        get{//..}
        set
        {
           //woot! a one line complex setter 
           BindCollection(value, ref this._Children, ref this.ehchildrenChanged, this.childrenChanged);
        }
    }
Run Code Online (Sandbox Code Playgroud)


Pet*_*lon 7

从C#规范:

当形式参数是引用参数时,方法调用中的相应参数必须包含关键字ref,后跟与形式参数相同类型的变量引用(第12.3.3节)