简体   繁体   中英

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 . 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.

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.

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. There is no reason why c# should restrict you from doing so. Likewise, you can create an instance of baseClass within baseClass itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM