Is there a better alternative than this to 'switch on type'?

后端 未结 30 3036
梦毁少年i
梦毁少年i 2020-11-22 03:28

Seeing as C# can\'t switch on a Type (which I gather wasn\'t added as a special case because is relationships mean that more than one distinct

30条回答
  •  忘掉有多难
    2020-11-22 04:09

    I agree with Jon about having a hash of actions to class name. If you keep your pattern, you might want to consider using the "as" construct instead:

    A a = o as A;
    if (a != null) {
        a.Hop();
        return;
    }
    B b = o as B;
    if (b != null) {
        b.Skip();
        return;
    }
    throw new ArgumentException("...");
    

    The difference is that when you use the patter if (foo is Bar) { ((Bar)foo).Action(); } you're doing the type casting twice. Now maybe the compiler will optimize and only do that work once - but I wouldn't count on it.

提交回复
热议问题