string[] txt1 = new string[]{"12","13"};
this.SetValue(txt1, v => Convert.ChangeType(v, typeof(decimal[]), null));
它抛出错误 - 对象必须实现 IConvertible。
我还想要一个代码将 string[] 转换为 Decimal[],int[],float[] .double[]
最佳答案
您不能像那样将字符串[] 直接转换为小数[] - 所有元素都必须单独转换为新类型。相反,您可以使用 Array.ConvertAll
string[] txt1 = new string[]{"12","13"};
decimal[] dec1 = Array.ConvertAll<string, decimal>(txt1, Convert.ToDecimal);
同样使用Convert.ToInt32
, Convert.ToSingle
, Convert.ToDouble
对于 Converter<TInput,TOutput>
生成 int[]、float[]、double[] 的参数,将正确的类型参数替换为 ConvertAll
编辑:由于您使用的是没有 ConvertAll 的 silverlight,因此您必须手动执行此操作:
decimal[] dec1 = new decimal[txt1.Length];
for (int i=0; i<txt1.Length; i++) {
dec1[i] = Convert.ToDecimal(txt1[i]);
}
关于c# - 在 c# 中将 string[] 转换为 Decimal[],int[],float[] .double[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1770626/