【发布时间】:2010-11-20 04:28:07
【问题描述】:
我有一个类框架。每个类代表一些实体并具有基本的静态方法:添加、获取、更新和删除。
这个方法是静态的,因为我想允许在不实例化对象的情况下执行一些操作。 例如,要添加一些对象,我必须这样做:Foo.Add(foo)。
现在我想要为每个类从另一个框架调用的方法数量。但是这些方法的功能是相同的:例如,我想检查对象是否存在以及是否不存在 - 创建,否则 - 更新。
实现它的最佳方法是什么?
我应该为每个班级都这样做吗:
例如:
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 更好(根据想法将所有代码放在一个地方)?
例如:
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);
}
}
什么方法更好更干净?或者您可能会建议另一种方法?
谢谢
【问题讨论】:
标签: c# frameworks static-methods