Quantcast
Channel: C#タグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 9747

C# で Between

$
0
0
はじめに ネットを探すとすぐに見つかるのですが、念のため自分用のスニペットを。 https://www.it-mure.jp.net/ja/c%23/c#に「between」関数はありますか?/971771777/ https://qiita.com/s_mino_ri/items/0fd2e2b3cebb7a62ad46 サンプルコード using System; namespace BetweenTest { static class Ext { public static bool Between<T>(this T source, T low, T high) where T : IComparable { return source.CompareTo(low) >= 0 && source.CompareTo(high) <= 0; } } class Program { static void Main(string[] args) { if (5.Between(0, 9)) { Console.WriteLine("Hello World!"); } if ("5".Between("0", "9")) { Console.WriteLine("Hello World!"); } } } } 使い所 VB では問題なくできるのですが、C# では以下のように書くとエラーになります。 if ("0" <= val && val <= "9") { // ... } 文字列の比較に <= とか書けないのです。こんな時に Between があると次のように書けるので助かります。 if (val.Between("0", "9")) { // ... }

Viewing all articles
Browse latest Browse all 9747

Trending Articles