English 中文(简体)
C#中采用可靠的基法
原标题:Make sure base method gets called in C#

Can 我在某种程度上强迫一个衍生的阶层总是把压倒性的方法基础称作主宰?

public class BaseClass
{
    public virtual void Update()
    {
        if(condition)
        {
            throw new Exception("..."); // Prevent derived method to be called
        }
    }
}

之后,在衍生产品类别中:

public override void Update()
{
    base.Update(); // Forced call

    // Do any work
}

我搜索并发现了一项建议,即使用非虚拟最新情况,但也使用受保护的虚拟最新情况。 仅仅看不出什么东西?

我希望你能够回答问题,我对任何坏的英语感到担忧。

最佳回答

使用template methods <——不超越需要做某些工作的基数方法,而是超越一个特定的范围,而这个范围可以是抽象的,也可以是基数。 (关于是否使之不可行或抽象的决定通常相当明显——作为具体类别,基类本身是否有意义?)

如同这一点一样,这基本上是你在<编码>上发现的模式——尽管它通常在<代码>上更新/code>,或者在我的经验中类似。 我认为,这种模式没有任何错误,它避免任何强迫所有衍生类别撰写相同的法典以称之为基法的想法。

问题回答

这使我略感了解最新情况和最新情况。 这里有一个可以帮助他人的法典例子。

public class BaseClass
{
    // This is the Update that class instances will use, it s never overridden by a subclass
    public void Update()
    {
        if(condition);
        // etc... base class code that will always run

        UpdateEx(); // ensure subclass Update() functionality is run
    }

    protected virtual void UpdateEx()
    {
        // does nothing unless sub-class overrides
    }
}

一个子类永远不会用于更新。 (a) 采用最新数据,在更新(更新)中增加执行;

public class ConcreteClass : BaseClass
{
    protected override void UpdateEx()
    {
        // implementation to be added to the BaseClass Update();
    }
}

具体目录的任何实例都将使用《基地地图集》和《具体目录》的更新版。

我认为,你认为的建议是好的。

唯一一种基类方法,你可以避免在基类建筑商中从子级调走。

我认为,有一个非虚拟基底成员,可以称之为可以扩大的虚拟“ook”,是解决此类问题的最常见办法。

视您的使用情况,您不妨使用<代码>event,但执行活动的一般模式是采用虚拟<代码>OnEvent方法,分级可优先于而不是增加活动手,例如,会oil倒同一东西。





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签