开发者

Using same base form for different entity classes

I'm currently working on a C# project where a main base form is derived by several other forms. Im using an entity class to handle data manipulation for every entity represented in the system: items, wharehouses, accounts, etc. That means that each of those derived forms is using its own kind of DAO.

I'm calling the base functionality from these derived forms just fine, what I'm strugling with right now is this: as each form has a different entity class I need a particular method for each derived class when the only di开发者_如何学编程fference between the base and the derived form is the type of entity class.

I have something like this:

        int id;
        int.TryParse(key.Text, out id);

        instance1 = adapter1.Populate(id);

        if (instance != null)
        {
            bindingSource.DataSource = instance1;
            this.GoEdit();
            this.MarkDeleted();
        }

So for example, what prevents me from using a generic version of this method to populate the entity class from my DB is that when defining those methods in the parent form I have to use the base class for my entities with no implementation so at the end I can't use a generic version.

Its bothering me that I have to copy this code over and over again (for each method of this kind) in the implementation of each derived form just to set the instance to the particular entity class. There should be another way and I hope anyone with a similar situation before could help me find a workaround..


How about putting a protected field in the base form to store a reference of the type of your base entity class. The constructors of the derived forms could set this field to the appropriate derived entity class. The code in your question could basically be just in the base form.


It seems like you might want to use an interface. This would allow you to implement classes that inherit from that interface but implement their own functionality for the Populate function.

Say you have the class structure below:

interface iPopulate
{
   void Populate(int id);
}

class MyBaseClass
{
  //whatever
}

class Warehouse : MyBaseClass, iPopulate
{
   void Populate(int id)
   {
       Console.WriteLine("Populate Warehouse");
   }
}

class Items : MyBaseClass, iPopulate
{
   void Populate(int id)
   {
      Console.WriteLine("Populate Item");
   }
}

You would be able to populate the data for each without specifying what the inherited class is. Example:

List<MyBaseClass> stuff = new List<MyBaseClass>();
stuff.Add(new Warehouse());
stuff.Add(new Items());
foreach(MyBaseClass i in stuff)
{
    int someId = 123;
    iPopulate pop = i as iPopulate;
    pop.Populate(someId);
}

This would output:

Populate Warehouse
Populate Item
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜