相关疑难解决方法(0)

将'enum'数组转换为'int'数组

我正在尝试将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)

出于好奇,有没有办法让这个工作不使用额外的方法?

问候

.net c#

36
推荐指数
4
解决办法
3万
查看次数

无法将值类型数组转换为params对象[]

如果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)

.net c#

26
推荐指数
2
解决办法
9348
查看次数

标签 统计

.net ×2

c# ×2