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

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

问题描述

如何强制子类实现其超类的某些属性?原因是我想使用 Attributes 来获取有关该类的一般信息,例如显示名称"、说明"或功能".

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.

是否有类似于方法的 abstract 属性?

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.

>

这是一些示例代码.

Here's some sample code for you.

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天全站免登陆