我正在尝试将Enum数组转换为int数组:
public enum TestEnum
{
Item1,
Item2
}
int[] result = Array.ConvertAll<TestEnum, int>(enumArray, new Converter<TestEnum, int>(Convert.ToInt32));
Run Code Online (Sandbox Code Playgroud)
出于某种原因,当在Array.ConvertAll中使用时,Convert.ToInt32不起作用,所以我不得不做一些更改:
int[] result = Array.ConvertAll<TestEnum, int>(enumArray, new Converter<TestEnum, int>(ConvertTestEnumToInt));
public static int ConvertTestEnumToInt(TestEnum te)
{
return (int)te;
}
Run Code Online (Sandbox Code Playgroud)
出于好奇,有没有办法让这个工作不使用额外的方法?
问候
如果C#可以将int转换为对象,为什么不将int []转换为对象[]?
void Main()
{
var a = new String[]{"0", "1"};
var b = new int[]{0, 1};
AssertMoreThan1(a); // No Exception
AssertMoreThan1(b); // Exception
}
static void AssertMoreThan1(params object[] v){
if(v.Length == 1){
throw new Exception("Too Few Parameters");
}
}
Run Code Online (Sandbox Code Playgroud)