C# - 更改覆盖方法的参数类型 [英] C# - Change argument type of override method

查看:28
本文介绍了C# - 更改覆盖方法的参数类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个继承类,我正在尝试将事件方法的参数类型更改为另一个类型,该类型也是继承类.

I have an inherited class and I am trying to change the event method's argument type to a different type that is also an inherited class.

原始类:

public class Alpha {
    protected virtual void OnSpecialEvent( AlphaArgs e );
}

public class AlphaArgs {
    public AlphaArgs ( int a, object b );

    public int A { get; }
    public object B { get; }
}

我的继承类:

public class Beta : Alpha {
    protected override void OnSpecialEvent ( BetaArgs e )
    {
        /* Do Stuff */
    }
}

public class BetaArgs : AlphaArgs {
    public BetaArgs (int a, object b, string c) : base (a, b)
    {
        /* Do Stuff */
    }

    public string C { get; }
}

但我最终遇到了错误:

CS0115  'Beta.OnSpecialEvent(BetaArgs)': no suitable method found to override

如果我使用 AlphaArgs,我没有任何问题",但我丢失了比我想添加的额外参数.

If I use AlphaArgs I don't have any 'problem' but I lose the extra parameter than I want to add.

有什么明显的我遗漏了,我什至不知道我在找什么......

Is there something obvious I'm missing, I don't even know what I'm looking for...

推荐答案

你可以使用泛型!看看:

public interface IBase<T>
    {
        void OnSpecialEvent(T e);
    }

    public class Alpha : IBase<AlphaArgs>
    {
        public void OnSpecialEvent(AlphaArgs e)
        {
            throw new NotImplementedException();
        }
    }

    public class Beta : IBase<BetaArgs>
    {
        public void OnSpecialEvent(BetaArgs e)
        {
            throw new NotImplementedException();
        }
    }

    public class AlphaArgs
    {
        public int A { get; }
        public object B { get; }
    }

    public class BetaArgs
    {
        public string C { get; }
    }

这篇关于C# - 更改覆盖方法的参数类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆