0

I have a framework of classes. Each class represents some entity and has basic static methods: Add, Get, Update and Delete.

This methods made static because i want to allow perform some action without instantiating of the object. E.g., to add some object i have to do this: Foo.Add(foo).

Now i want to have number of methods which would be invoked from another framework for every class. But the functionality of this methods will be the same: for example i want to check if object exists and if it doesn't - create, otherwise - update.

What is the best approach to implement it?

Should i do it in this way for every class:

E.g.:

public void DoSomethingWithFoo(Foo foo)
{
    if (Foo.Get(foo.id) != null)
        Foo.Update(foo);
    else
        Foo.Add(foo);
}

public void DoSomethingWithBar(Bar bar)
{
    if (Bar.Get(bar.id) != null)
        Bar.Update(bar);
    else
        Bar.Add(bar);
}

Or is it better to do it using InvokeMember(according to idea to have all the code in one place)?

E.g.:

   public void DoSomethingWithFoo(Foo foo)
   {
       DoSomethingWithObject(foo);
   }  

   private void DoSomethingWithObject(object obj)
    {
        Type type = obj.GetType();

        object[] args = {type.GetProperty("ID").GetValue(obj, null)};
        object[] args2 = { obj };
        if (type.InvokeMember("Get", BindingFlags.Default | BindingFlags.InvokeMethod, null, null, args) != null)
        {
            type.InvokeMember("Update", BindingFlags.Default | BindingFlags.InvokeMethod, null, null, args2);
        }
        else
        {
            type.InvokeMember("Add", BindingFlags.Default | BindingFlags.InvokeMethod, null, null, args2);
        }
    }

What approach is better and more cleaner? Or maybe you will suggest another approach?

Thanks

4

1 回答 1

0

出色地。

我的意思是我首先要说不要编写自己的实体框架并使用LLBLGen之类的东西。

其次我会说,如果你忽略这个建议,你想要一些超级类,比如

public abstract class SavableBase
{
  protected abstract void Add ();
  protected abstract void Update ();

  public void Save ()
  {
     if( !saved ){
        Add();
     } else {
        Update();
     }
  }
}

然后适当地实施这些方法。

于 2009-08-17T09:06:13.277 回答