同时创建子类和对象
我正在寻找与 Java 习惯用法等效的 C# 语言。
在Java中,如果你有一个抽象类,你不能直接创建该类的对象;您需要首先对其进行子类化(并提供抽象方法的重写)。但实际上您可以同时创建子类和对象:
public abstract class Type {
abstract Kind kind();
public static final Type BOOLEAN =
new Type() {
@Override
Kind kind() {
return Kind.BOOLEAN;
}
};
上面的内容并未逐字翻译为 C#;有等效的习语吗?或者您只需要手写出来,首先声明一个命名子类,然后创建该子类的对象?
I am looking for a C# equivalent of a Java idiom.
In Java, if you have an abstract class, you cannot directly create an object of that class; you need to subclass it (and provide an override of the abstract methods) first. But you can actually create the subclass and object at the same time:
public abstract class Type {
abstract Kind kind();
public static final Type BOOLEAN =
new Type() {
@Override
Kind kind() {
return Kind.BOOLEAN;
}
};
The above doesn't translate verbatim into C#; is there an equivalent idiom? Or do you just need to write it out longhand, declaring a named subclass first, then creating an object of the subclass?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不幸的是没有。也许您可以尝试创建一个实现您的类
Type
的私有类,然后创建一个返回该类的方法?但是,也许看看您想要实现的内容。这可能不适合您的问题。
Unfortunately not. Maybe you can try making a private class which implements your class
Type
and then make a method that returns that?However, maybe take a look at what you're trying to implement. This might not be the right pattern for your problem.