且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

基类可以确定派生类是否重写了虚拟成员吗?

更新时间:2023-02-14 23:01:30

如果您定义了一个抽象Task和一个IHasSharedData接口,该怎么办,然后在Method中检查派生Task在执行锁定之前是否实现了IHasSharedData.仅实现接口的类需要等待.我意识到这避免了回答实际问题,但是我认为这比使用反射是一种更干净的解决方案.希望您会为该接口找到一个更好的名称,该名称与类的实际行为更紧密地匹配.

What if you defined an abstract Task and a IHasSharedData interface, then in Method you check if the derived Task implements IHasSharedData before doing the lock. Only classes that implement the interface need wait. I realize that this avoids answering the actual question, but I think it would be a cleaner solution than using reflection. Hopefully, you'd find a better name for the interface that more closely matches what the classes actually do.

public interface IHasSharedData
{
    void UpdateSharedData();
}

public abstract class Task
{
    private static object LockObject = new object();

    protected virtual void UpdateNonSharedData() { }

    public void Method()
    {
         if (this is IHasSharedData)
         {
            lock(LockObject)
            {
                UpdateSharedData();
            }
         }
         UpdateNonSharedData();
    }
}

public class SharedDataTask : Task, IHasSharedData
{
    public void UpdateSharedData()
    {
       ...
    }
}