[英]derived instance in base class
class baseClass
{
derivedClass nm = new derivedClass();
}
class derivedClass : baseClass
{
}
This code builds fine. 这段代码很好。 What might be the possible reason for C# to allow creating
derivedClass
objects in baseClass
. C#允许在
baseClass
创建derivedClass
对象的可能原因是什么。 Can you think of any specific reasons for doing this? 你能想到这样做的具体原因吗?
This code builds fine.
这段代码很好。
Yes - why do you think it wouldn't? 是的 - 为什么你认为不会?
What might be the possible reason for C# to allow creating derivedClass objects in baseClass.
C#允许在baseClass中创建derivedClass对象的可能原因是什么。
Because there's no reason to prohibit it? 因为没有理由禁止它吗?
Can you think of any specific reasons for doing this?
你能想到这样做的具体原因吗?
Static factory methods, for example? 例如,静态工厂方法?
// BaseClass gets to decide which concrete class to return
public static BaseClass GetInstance()
{
return new DerivedClass();
}
That's actually a pretty common pattern. 这实际上是一种非常常见的模式。 We use it a lot in Noda Time for example, where
CalendarSystem
is a public abstract class, but all the concrete derived classes are internal. 我们在Noda Time中使用它很多,例如
CalendarSystem
是一个公共抽象类,但所有具体的派生类都是内部的。
Sure, it's crazy to have the exact example you've given - with an instance field initializing itself by creating an instance of a derived class - because it would blow up the stack due to recursion - but that's not a matter of it being a derived class. 当然,拥有你给出的确切示例是很疯狂的 - 实例字段通过创建派生类的实例来初始化自己 - 因为它会因递归而炸毁堆栈 - 但这不是它是派生的问题类。 You'd get the same thing by initializing the same class:
你可以通过初始化同一个类来获得相同的东西:
class Bang
{
// Recursively call constructor until the stack overflows.
Bang bang = new Bang();
}
A developer I used to work with produced this code in our codebase. 我以前使用的开发人员在我们的代码库中生成了这段代码。 I personally agree its useful.
我个人认为它很有用。
public class Foo
{
public static Foo MagicalFooValue
{
get { return Bar.Instance; }
}
private class Bar : Foo
{
//Implemented as a private singleton
}
}
一个明显的例子是在基类中有一个工厂方法,根据某些条件返回适当的实现。
derivedClass
can be instantiated in baseClass
because it is an accessible class. derivedClass
可以在baseClass
中实例化,因为它是一个可访问的类。 There is no reason why c# should restrict you from doing so. c#没有理由限制你这样做。 Likewise, you can create an instance of
baseClass
within baseClass
itself. 同样,您可以在
baseClass
创建一个baseClass
实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.