帮助我重构一个泛型集合的迭代

Bis*_*ath 2 c# generics refactoring

我说我正在使用通用数据结构MyGeneric<Type>.有一种情况我必须迭代它所拥有的所有值

我正在尝试的代码.

for ( all the keys in myGeneric ) {
    // do lot of stuff here 
}
Run Code Online (Sandbox Code Playgroud)

现在泛型可以将基类型保存为double和string,它也可以保存一些用户定义的类型.在某种特殊情况下,我必须根据通用类型进行一些特定的工作.

所以最终的代码块看起来像这样

for( all the keys in myGeneric ) {
    if key is type foo then 
        //do foo foo 
    else if key is of type bar 
        //do bar bar 
}
Run Code Online (Sandbox Code Playgroud)

现在,由于我的复杂性很敏感,我不喜欢在for循环中有if条件.所以我做的下一个解决方案是

if myGeneric is of type foo 
    call fooIterator(myGeneric) 
if myGenric is of type bar 
    call barItetrator(myGeneric)


function FooIterator() {
    // .....
    // foo work 
    //......
}

function BarItetrator() {
    // .....
    // bar work 
    //......
}
Run Code Online (Sandbox Code Playgroud)

然后,当有人看到我的代码时,我很确定他们会喊"重构"在哪里.

在这种情况下,理想的做法是什么?

谢谢.

Mar*_*ell 7

那么,您可以使用Linq OfType<T>方法和多个循环吗?

foreach(Foo foo in list.OfType<Foo>()) {
  //
}
foreach(Bar bar in list.OfType<Bar>()) {
  //
}
Run Code Online (Sandbox Code Playgroud)

除此之外,你还有条件陈述.我确实在这里看到了与F#相关的内容,它更干净地做到了这一点.

作为旁白; 如果这是使用PushLINQ(在MiscUtil中)你可以在一次迭代中通过不同的分支推送不同的类型来做到这一点 - 不确定它只是为此保证.