Best way to create objects in C #

I have an application with my types of objects that inherit from a base class that contains most of the properties for application objects. All types of objects are stored in one table in the database. The "ClassType" column determines which type of object I passed to the SqlDataReader string.

Here is my current implementation:

SqlDataReader dr = SqlServerHelper.ExecuteReader("MyStoreProc", MySqlParmas);

if(dr.HasRows)
{
    while(dr.Read())
    {
        switch(dr["ClassType"].ToString())
        {
            case "ClassA":
                //cast sqldatareader a ClassA object
                ClassA a = new ClassFactory.CreateClassA(object p1, object p2);
            case "ClassB":
                //cast sqldatareader a ClassB object
                ClassB b = new ClassFactory.CreateClassB(object p1, object p2);
        //it continues for all objects with app....
        }
    }
}

dr.Close()

My question is, what is their best implementation for this type of processing?

+3
source share
5 answers

This approach is that you do not want to switch to ORM generating code.

In your feature table, specify the fully qualified name of the feature type.

Then you can do something like:

    private Dictionary<String, Type> _objectTypes = new Dictionary<String, Type>();

    public ObjectFactory()
    {
        // Preload the Object Types into a dictionary so we can look them up later
        foreach (Type type in typeof(ObjectFactory).Assembly.GetTypes())
        {
            if (type.IsSubclassOf(typeof(BaseEntity)))
            {
                _objectTypes[type.Name.ToLower()] = type;
            }
        }
    }

Now that you have all the preloaded maps, you can replace your code:

    string objectName = dr["ClassType"].ToString().ToLower();
    Type objectType;

    if (_objectTypes.TryGetValue(objectName, out objectType))
    {
       return (BaseEntity)Activator.CreateInstance(objectType,reader);
    }        

, , factory.

+6

, Object-Relational Mapper . NHibernate ORM- .NET.

+5

LINQ to SQL . , , . .

0

, , , .

@ :

:

public class BaseClass
{
    public BaseClass() { }

    public object p1 { get; set;}

    public object p2 { get; set; }

    public virtual void ImplementLogic()  
    {
        //do some fun stuff....
    }
}

public class ClassA : BaseClass
{
    public ClassA { }

    public override void ImplementLogic()
    {
        //make it rain.....
    }
} 

public class ClassB : BaseClass
{
    public ClassB { }    

    public override void ImplementLogic()
    {
        //do some more fun stuff
    }
}

?

BaseClassFactory, , BaseClass?

0

You can save the fully qualified type name in your database, and then create it with Activator.GetInstance. This saves you the ugly switch statement, but calls the type constructor instead of the factory method. Will this do what you want?

0
source

All Articles