繁体   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