C#,实现“静态抽象"之类的方法 [英] C#, implement 'static abstract' like methods

查看:27
本文介绍了C#,实现“静态抽象"之类的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近遇到了一个问题,我似乎需要一个静态抽象"方法.我知道为什么这是不可能的,但我该如何解决这个限制?

I recently ran into a problem where it seems I need a 'static abstract' method. I know why it is impossible, but how can I work around this limitation?

例如我有一个抽象类,它有一个描述字符串.由于这个字符串对所有实例都是通用的,所以它被标记为静态,但我想要求从这个类派生的所有类都提供自己的 Description 属性,所以我将它标记为抽象:

For example I have an abstract class which has a description string. Since this string is common for all instances, it is marked as static, but I want to require that all classes derived from this class provide their own Description property so I marked it as abstract:

abstract class AbstractBase
{
    ...
    public static abstract string Description{get;}
    ...
}

它当然不会编译.我想过使用接口,但接口可能不包含静态方法签名.

It won't compile of course. I thought of using interfaces but interfaces may not contain static method signatures.

我是否应该简单地将其设为非静态,并始终获取一个实例来获取该类的特定信息?

Should I make it simply non-static, and always get an instance to get that class specific information?

有什么想法吗?

推荐答案

static 和 abstract 的结合有点没有意义,是的.静态背后的想法是不需要提供类的实例来使用有问题的成员;但是对于抽象,人们期望一个实例是提供具体实现的派生类.

Combining static and abstract is somewhat meaningless, yes. The idea behind static is one need not present an instance of the class in order to use the member in question; however with abstract, one expects an instance to be of a derived class that provides a concrete implementation.

我明白你为什么想要这种组合,但事实是唯一的效果是拒绝实现使用this"或任何非静态成员.也就是说,父类会在派生类的实现中规定一个限制,即使调用抽象或静态抽象"成员之间没有根本区别(因为两者都需要一个具体的实例来确定要使用的实现)

I can see why you'd want this sort of combination, but the fact is the only effect would be to deny the implementation use of 'this' or any non-static members. That is, the parent class would dictate a restriction in the implementation of the derived class, even though there's no underlying difference between calling an abstract or 'static abstract' member (as both would need a concrete instance to figure out what implementation to use)

这篇关于C#,实现“静态抽象"之类的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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