请考虑两个限制 -
- 无法将 MyProperty 移动到接口或抽象类。
- FooEventHandler 是一个 dotnet 框架方法,因此不能更改参数类型。
我在几个类中定义了 MyProperty。
class A
{
public string MyProperty { get; set; }
}
class B
{
public string MyProperty { get; set; }
}
class C
{
public string MyProperty { get; set; }
}
FooEventHandler 方法为它接收到的所有参数更新此属性。
public object FooEventHandler(object obj)
{
object toReturn = null;
if (obj.GetType() == typeof(A))
{
(obj as A).MyProperty = "updated";
toReturn = obj;
}
else if (obj.GetType() == typeof(B))
{
(obj as B).MyProperty = "updated";
toReturn = obj;
}
else if (obj.GetType() == typeof(C))
{
(obj as C).MyProperty = "updated";
toReturn = obj;
}
return toReturn;
}
并且 FooEventHandler 像这样反复调用 -
static void Main(string[] args)
{
Program program = new Program();
A objA = new A();
program.FooEventHandler(objA);
B objB = new B();
program.FooEventHandler(objB);
C objC = new C();
program.FooEventHandler(objC);
}
请提出一种删除 Foo 中冗余代码的方法,考虑到上述两个限制。
更准确地说,我在 WCF 中使用 ParameterInspector 时遇到了这个问题。我正在尝试修改此处截获的所有请求的属性,并且必须根据 operationName 编写 Switch Case。
如上所述的A、B、C、D类是代理。所以不想一开始就修改它们。由于更新服务参考将覆盖我的 iterface 更改。
public object BeforeCall(string operationName, object[] inputs){
// update inputs[0] properties
}
谢谢您的帮助。