C #: Common Heritable Plants

I have a base class that takes one general argument. Then I have several classes that inherit from this base class. Is there an easy way for child classes to embed a factory from a base class?

Example

class BaseClass<T>
{
     T Value {get; set;}
     string Name {get; set;}

     public static BaseClass<T> Factory(T Value)
     {
        return new BaseClass<T>(Value); 
     }
}

class ChildClass : BaseClass<int>
{
     public void Test()
     {
         // I want this below to work
         // but Factory() returns a BaseClass
         ChildClass bs = ChildClass.Factory(10);
     }
}

In the code, I noticed that I want to work. I can think of one way to overcome this by adding an implicit statement in BaseClass or SubClass that converts from BaseClass to ChildClass.

I can also just explicitly add a factory to ChildClass, but that defeats the point of inheritance.

Is there a better, more standardized way to do this?

+3
source share
2 answers

I would do something like this:

class BaseClass<T, K> where K : BaseClass<T, K>, new()
{
    T Value { get; set; }
    string Name { get; set; }

    public static K Factory(T value)
    {
        return new K { Value = value };
    }
}

class ChildClass : BaseClass<int, ChildClass>
{
    public void Test()
    {
        ChildClass cs = Factory(10);
    }
}
+8
source

, , , . , .

factory , . ? , . , ChildClass?

factory, . , singleton, factory, .

class MyFactory
{
    private static IMyFactory _instance;
    public static void Assign(IMyFactory factory) { _instance = factory; }
    public static T Create<T>() { return _instance.Create<T>(); }
}

interface IMyFactory
{
    T Create<T>();
}
class MyFactoryImp : IMyFactory
{
    //do whatever needed in here
    public T Create<T>(){ return new T(); }
}


class BaseClass<T>
{
     T Value {get; set;}
     string Name {get; set;}
}

class ChildClass : BaseClass<int>
{
     public void Test()
     {
         ChildClass bs = MyFactory.Create<ChildClass>(10);
     }
}

// start with this, you can easily switch implementation
MyFactory.Assign(new MyFactoryImp());

, autofac.

0

Source: https://habr.com/ru/post/1793516/


All Articles