寻找一种设计模式来取代huuuge如果对象类型

mci*_*321 8 generics design-patterns dependency-injection

好的,所以我正在寻找一些看起来大致如下的代码:

void DoSomething(object o)
{
    if (o is Sometype1) { 
    //cast o to Sometype and do something to it
    }
    else if (o is Sometype2) {
    //cast o to Sometype2 and do something to it
    }
    ...
    else if (o is SometypeN) {
    //cast o to SometypeN and do something to it
    }
}
Run Code Online (Sandbox Code Playgroud)

现在一种方法是使所有o用作参数的对象实现类似的接口

interface ICanHaveSomethingDoneToMe
{
    //expose various properties that the DoSomething method wants to access
}
Run Code Online (Sandbox Code Playgroud)

但问题是我不希望我的所有对象都实现这个接口 - 做某事的逻辑并不真正属于他们.我应该使用什么模式来处理这个问题?

我怀疑像是一系列的实现

interface IPropertiesForDoingSomethingTo<T>
{
    //expose various properties that the DoSomething method wants to access
}
Run Code Online (Sandbox Code Playgroud)

可能会更好.我有一个针对我想要做的每个对象类型的实现,但后来我遇到了这个新问题.我需要有一个像这样的方法

IPropertiesForDoingSomethingTo<T> GetPropsGeneric(T t);
Run Code Online (Sandbox Code Playgroud)

但这是否需要对其进行大规模切换?我应该用类似的方法定义一个类

IPropertiesForDoingSomethingTo<Someobject1> GetProps(Someobject1 t);
...
IPropertiesForDoingSomethingTo<Someobject1> GetProps(SomeobjectN t);
Run Code Online (Sandbox Code Playgroud)

与在运行时无法添加新类型的通用版本相比,这会产生问题.是否有人可以使用GetPropsGeneric中的DI容器解决容器?谢谢!

Ste*_*owe 6

每次看到正在检查对象类型的switch语句(或一系列if语句)时,这都是缺少基类或接口的Big Red Flag.换句话说,代码应该依赖于多态,而不是测试对象类型

如果你不能改变基类或实现一个接口,你可能会留下一个字典来模拟动态调度.在C#中,您可以对包含强制转换的方法使用匿名委托

至于属性访问,如果属性不符合并且通过反射访问不是一个选项,您可能需要在上面的方法/委托中提取属性值并将它们传递给泛型函数