簡體   English   中英

Delphi的C#等價物

[英]C# equivalent for Delphi's in

對於Delphi的語法,C#中的等價物是什么,如:


  if (iIntVar in [2,96]) then 
  begin
    //some code
  end;

謝謝

我更喜歡這里定義的方法: 將變量與多個值進行比較

這是乍得帖子的轉換:

public static bool In(this T obj, params T[] arr)
{
    return arr.Contains(obj);
}

用法就是

if (intVar.In(12, 42, 46, 74) ) 
{ 
    //TODO: Something 
} 

要么

if (42.In(x, y, z))
    // do something

沒有這樣的等價物。 最接近的是集合的Contains()擴展方法。

例:

var vals = new int[] {2, 96};
if(vals.Contains(iIntVar))
{
  // some code
}

在.Net中,.Contains是最接近的,但語法與你寫的相反。

您可以編寫一個擴展方法來創建.In方法

public static bool In<T>(this T obj, IEnumerable<T> arr)
 {
  return arr.Contains(obj);
 }

用法就是

if (42.In(new[] { 12, 42, 46, 74 }) )
{
    //TODO: Something
}

您可以創建此擴展方法:

public static class ExtensionMethods
{
    public static bool InRange(this int val, int lower, int upper)
    {
        return val >= lower && val <= upper;
    }
}

然后你可以這樣做:

int i = 56;
if (i.InRange(2, 96)) { /* ... */ }

為了擴展Mason Wheeler在評論中所寫的內容,這將是HashSet <T> .Contains(在.NET 3.5下)。

int i = 96;
var set = new HashSet<int> { 2, 96 };

if (set.Contains(i))
{
   Console.WriteLine("Found!");
}

你可以寫一個擴展方法

 public static bool In(this int value, int[] range)
    {
        return (value >= range[0] && value <= range[1]);
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM