C #: determining the type of a derived object from a static method of a base class

In a C # program, I have an abstract base class with the static "Create" method. The Create method is used to create an instance of the class and store it locally for later use. Since the base class is abstract, implementation objects will always be extracted from it.

I want to get an object from the base class, call the static Create method (implemented once in the base class) through the derived class and create an instance of the derived object.

Are there any tools in C # that will allow me to remove this. My current fallback position is to pass an instance of the derived class as one of the arguments to the Create function, i.e.:

objDerived.Create(new objDerived(), "Arg1", "Arg2");
+5
source share
6 answers

Try using generics:

public static BaseClass Create<T>() where T : BaseClass, new()
{
    T newVar = new T();
    // Do something with newVar
    return T;
}

Using an example:

DerivedClass d = BaseClass.Create<DerivedClass>();
+12
source

Summary

There are two main options. More enjoyable and new is the use of generics, while the other is the use of reflection. I provide both options if you need to develop a solution that works before .NET 2.0.

Generics

abstract class BaseClass
{
  public static BaseClass Create<T>() where T : BaseClass, new()
  {
    return new T();
  }
}

Where to be used:

DerivedClass derivedInstance = BaseClass.Create<DerivedClass>();

Reflection

abstract class BaseClass
{
  public static BaseClass Create(Type derivedType)
  {
    // Cast will throw at runtime if the created class
    // doesn't derive from BaseClass.
    return (BaseClass)Activator.CreateInstance(derivedType);
  }
}

If there will be a use (division into two lines for readability):

DerivedClass derivedClass
    = (DerivedClass)BaseClass.Create(typeof(DerivedClass));
+5
source

, factory ? , , ... ...

 public abstract class MyBase
 {
    public static T GetNewDerived<T>() where T : MyBase, new()
    {
        return new T();
    }    
 }
 public class DerivedA : MyBase
 {
    public static DerivedA GetNewDerived()
    {
        return GetNewDerived<DerivedA>();
    }
 }

 public class DerivedB : MyBase
 {
    public static DerivedB GetNewDerived()
    {
        return GetNewDerived<DerivedB>();
    }
 }     

, ?

+4

, Create(). , . Init(), , , , .

+3

; , , . , ; , . - .

+1

I'm not sure what your design goals are, but from what you asked for, it seems like this could lead to a big smell of code. I think you should really take a look at the management inversion (IoC) / dependency (DI) design patterns that are implemented in many environments such as Microsoft Unity, Castle Windsor, StructureMap, Ninject, Spring.Net, etc.

I think if you look at using an IoC container, it will solve your problem in a much cleaner and loosely coupled way.

0
source

All Articles