我有一个类框架。每个类代表一些实体,并具有基本的静态方法:添加,获取,更新和删除。
这个方法是静态的,因为我想允许在没有实例化对象的情况下执行某些操作。 例如,添加一些对象我必须这样做:Foo.Add(foo)。
现在我希望有一些方法可以从每个类的另一个框架调用。但是这个方法的功能是相同的:例如,我想检查对象是否存在,如果不存在 - 创建,否则 - 更新。
实施它的最佳方法是什么?
我是否应该以这种方式为每个班级做这件事:
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);
}
或者使用InvokeMember更好(根据想法将所有代码放在一个地方)?
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);
}
}
哪种方法更好,更清洁?或许你会建议另一种方法?
由于
答案 0 :(得分:0)
好。
我的意思是我首先要说的是不要编写自己的实体框架并使用类似LLBLGen的内容。
其次我会说,如果你忽略了这个建议,你想要一些像
这样的超类public abstract class SavableBase
{
protected abstract void Add ();
protected abstract void Update ();
public void Save ()
{
if( !saved ){
Add();
} else {
Update();
}
}
}
然后适当地实施这些方法。