简体   繁体   中英

Passing different objects of the same parent class to a constructor/method that hosts a generic derived class object

We have the parent class

public class ParentClass
{
    int GeneralVariable;
}

then a derived class (just a class that holds information)

public class DerivedClassOne : ParentClass
{
    int DerivedSpecificVariableOne;
}

then another derived class (just a class that holds information)

public class DerivedClassTwo : ParentClass
{
    int DerivedSpecificVariableTwo;
}

Then a class that can "house" only one of these 2 derived classes:

public class HousingClass : UnrelatedImportantClass
{
    public void DoWorkingOnDerivedClasses(){}
}

Then a class that hosts everything. HostClass will call methods on HousingClass to do work on DerivedClass

public class HostClass
{
    List<HousingClass> Housings = new List<HousingClass>();
}

In this housing class, I'd like to be able to "house" either DerivedClassOne, or DerivedClassTwo, and to be able to "do work" on either of the derived classes. Ideally, I'd like to not have to potentially have a ton of overloaded c-tors or methods, with a ton of class variables defining different derived classes. Right now, that's how the "Housing" class is looking, and I foresee it becoming unwieldy and hard to maintain in the near future.

Ultimately, what design principle am I after, and simple case what could that look like? Right now the ParentClass is not Abstract, but would that help in what I'm after?

Generic class would partially satisfy your requirements - your "housing" class would still be limited to using "parent" methods, but outside callers would be able to use methods/properties of correct derived class.

public class HousingClass<T> where T : ParentClass
{
    public T Derived {get;set;}

    public void Method()
    {
      // can only use methods/properties from ParentClass
      Console.WriteLine(Derived.GeneralVariable);
    }
}

You will be able to use exact type of Derived outside the class so:

DerivedClassOne d = new DerivedClassOne();
HousingClass<DerivedClassOne> house = new HousingClass<DerivedClassOne>
     {  Derived = d };
house.Derived.DerivedSpecificVariableOne = 42; 

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