[英]Cast Int Array to Enum Flags
I have the following enum with flags: 我有以下带标志的枚举:
[Flags]
public enum DataFiat {
Public = 1,
Listed = 2,
Client = 4
} // DataFiat
And I have an int array, for example: 我有一个int数组,例如:
int[] selected = new int[] { 1, 4 }
How can I convert this to my enum which would become: 如何将此转换为我的枚举,这将成为:
DataFiat.Public | DataFiat.Client
Thank You, Miguel 谢谢你,米格尔
var f = (DataFiat)selected.Sum();
怎么样的
var tt = (DataFiat)selected.Aggregate((i, t) => i | t);
this snippet: 这个片段:
var intArr = new[] { 1, 4 };
var sum = intArr.Sum(x => x);
var result = (Test)sum;
returns 回报
DataFlat result = (DataFlat) 0;
foreach (var value in selected)
{
result |= (DataFlat)value;
}
Or if you want to use LINQ 或者如果你想使用LINQ
DataFlat result = (DataFlat) selected.Aggregate(0, (old, current) => old | current);
You mean this? 你是这个意思?
IEnumerable<DataFiat> selectedDataFiats = selected.Cast<DataFiat>();
This sinmply casts each int
to DataFiat
. 这可以将每个
int
转换为DataFiat
。
You can't just cast the array, if it's really an object[]. 如果它真的是一个对象[],你不能只是转换数组。 You can create a new array pretty easily though:
您可以非常轻松地创建新数组:
var enumArray = originalArray.Cast<DataFiat>().ToArray();
If it were actually an int[] array to start with, you could cast - although you'd have to talk nicely to the C# compiler first: 如果它实际上是一个int []数组,那么你可以进行转换 - 尽管你必须先与C#编译器进行良好的讨论:
using System;
class Program
{
enum Foo
{
Bar = 1,
Baz = 2
}
static void Main()
{
int[] ints = new int[] { 1, 2 };
Foo[] foos = (Foo[]) (object) ints;
foreach (var foo in foos)
{
Console.WriteLine(foo);
}
}
}
The C# compiler doesn't believe that there's a conversion from int[] to Foo[] (and there isn't, within the rules of C#)... but the CLR is fine with this conversion, so as long as you can persuade the C# compiler to play along (by casting to object first) it's fine. C#编译器不相信从int []到Foo []的转换(并且在C#的规则中没有)...但是CLR对于这种转换是好的,所以只要你能说服C#编译器一起玩(通过先铸造到对象)就可以了。
This doesn't work when the original array is really an object[] though. 当原始数组实际上是一个对象[]时,这不起作用。
Hope this helps.. 希望这可以帮助..
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.