Methods of simplifying ugly nested if-else trees in C#

前端 未结 11 672
野性不改
野性不改 2021-02-02 04:23

Sometimes I\'m writing ugly if-else statements in C# 3.5; I\'m aware of some different approaches to simplifying that with table-driven development, class hierarchy, anonimous m

11条回答
  •  醉梦人生
    2021-02-02 04:44

    Not a C# answer, but you probably would like pattern matching. With pattern matching, you can take several inputs, and do simultaneous matches on all of them. For example (F#):

    let x=
      match cond1, cond2, name with
      | _, _, "Bob"     -> 9000 // Bob gets 9000, regardless of cond1 or 2
      | false, false, _ -> 0 
      | true, false, _  -> 1
      | false, true, _  -> 2
      | true, true, ""  -> 0 // Both conds but no name gets 0
      | true, true, _   -> 3 // Cond1&2 give 3
    

    You can express any combination to create a match (this just scratches the surface). However, C# doesn't support this, and I doubt it will any time soon. Meanwhile, there are some attempts to try this in C#, such as here: http://codebetter.com/blogs/matthew.podwysocki/archive/2008/09/16/functional-c-pattern-matching.aspx. Google can turn up many more; perhaps one will suit you.

提交回复
热议问题