C#将方法隐式转换为自定义类型

时间:2018-09-11 07:40:01

标签: c# casting delegates implicit

我希望能够隐式地将方法强制转换为自己定义的类型。

采用以下代码(我省略了一堆无关的代码):

public abstract class Callback_Base
{
    // Omitted code.
}

public abstract class VoidCallback : Callback_Base
{
    // Omitted code.

    public delegate void Signature();
    public abstract void Run();

    public static implicit operator VoidCallback(Signature callback) { return new BindableVoidCallback(callback); }
}

public class BindableVoidCallback : VoidCallback
{
    protected Signature m_Callback;

    public BindableVoidCallback() : this(null) {}
    public BindableVoidCallback(Signature callback)
    {
        m_Callback = callback;
    }

    public override void Run() { InvokeSafe(); }

    public bool IsBound() { return m_Callback != null; }
    public void Invoke() { m_Callback(); }
    public void InvokeSafe()
    {
        if (IsBound())
            Invoke();
    }

    // Omitted code.
}

然后,我希望以下所有内容都能正常工作。

public class MyClass
{
    private void Main()
    {
        // Works
        Action a = Main;
        VoidCallback.Signature s = Main;
        VoidCallback cb0 = s;
        VoidCallback cb1 = (VoidCallback)Main;
        Do(Main);
        DoCb(s);

        // Doesn't work, but would like to work (resolves properly to the implicit operator but doesn't compile).
        VoidCallback cb2 = Main;
        // Doesn't work either.
        s = (VoidCallback.Signature)a;
    }

    private void Do(VoidCallback.Signature test)
    {

    }
    private void DoCb(VoidCallback test)
    {

    }
}

我对为什么Do(Main)用VoidCallback.Signature进行编译有些傻眼,但隐式转换运算符无法使用相同的方法。

0 个答案:

没有答案