在抽象超类的子类中强制使用属性 [英] Force attribute usage in subclass of abstract superclass

查看:92
本文介绍了在抽象超类的子类中强制使用属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何强制子类实现其超类的某些属性?原因是我想使用Attributes来获取有关该类的一般信息,例如DisplayName,Description或Capabilities。

How can I force a subclass to implement certain Attributes of its superclass? The reason is that I want to use Attributes for general information about the class, e.g. "DisplayName", "Description" or "Capabilities".

所以我想我可以在超类中实现它们并强制子类实现属性。

So I thought I might implement them in a superclass and force the subclasses to implement the attributes.

是否有类似抽象属性的方法?

Is there something like an abstract attribute like for methods?

[abstract DeclareMe]
public abstract class InheritMe {
    public abstract void DeclareMe();
}


推荐答案

因为你的班级必须运行迟早,您可以向基类添加检查机制,以验证子类中某些属性的存在。

As your class must be run sooner or later, you can add checking mechanism to your base class to verify the existance of certain attributes in your sub classes.

以下是一些示例代码。

class Program
{
    static void Main(string[] args)
    {
        var a = new SubA();
        var b = new SubB();
    }
}

class BaseClass
{
    public BaseClass()
    {
        Type t = GetType();
        if (t.IsDefined(typeof(SerializableAttribute), false) == false)
        {
            Console.WriteLine("bad implementation");
            throw new InvalidOperationException();
        }
        Console.WriteLine("good implementation");
    }
}

[Serializable]
class SubA : BaseClass
{ }

class SubB : BaseClass
{ }

最后一句话,不要太在意自己。一旦我做了我的设计,我一直认为我可能会以错误的顺序调用两种方法或忘记做某事,然后我将一个简单的设计变成一个复杂的设计以防止我可能的错误。后来我扔掉了警卫,只是抛出异常,用于检测意外情况的代码被 #if DEBUG 包围。

The last word, don't be too wary of yourself. Once I was doing my design, I always thought I might call two methods in a wrong order or forget to do something, then I turned a simple design into a complicated one to prevent my possible mistakes. Later I threw away the guards, just throwing Exceptions and the code used to detect unexpected situations were surrounded by #if DEBUG.

这篇关于在抽象超类的子类中强制使用属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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