Can .NET convert “Yes” & “No” to boolean without If?

后端 未结 12 664
情话喂你
情话喂你 2020-12-17 14:15

You would think there would be a way using DirectCast, TryCast, CType etc but all of them seem to choke on it e.g.:

CType(\"Yes\", Boolean)

12条回答
  •  既然无缘
    2020-12-17 14:57

    Using this way, you can define conversions from any string you like, to the boolean value you need. 1 is true, 0 is false, obviously.
    Benefits: Easily modified. You can add new aliases or remove them very easily.
    Cons: Will probably take longer than a simple if. (But if you have multiple alises, it will get hairy)

    enum BooleanAliases {
          Yes = 1,
          Aye = 1,
          Cool = 1,
          Naw = 0,
          No = 0
     }
     static bool FromString(string str) {
          return Convert.ToBoolean(Enum.Parse(typeof(BooleanAliases), str));
     }
     // FromString("Yes") = true
     // FromString("No") = false
     // FromString("Cool") = true
    

提交回复
热议问题