如何在C#中将对象转换为可空的int数组?
我想在c#中将对象类型转换为nullable int array(int?[])但是我没有得到解决方案,任何人都知道如何做到这一点。
Hi,
I want to convert object type to nullable int array (int?[]) in c# but I am not getting nay solution, can anyone know how to do this.
int?[] NullableIntArray{get;set;}
object value = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
NullableIntArray = value;
((IEnumerable)propertyValue).Cast<object>().Select(x => x.ToString()).ToArray(); using this I can convert object to string array
where
propertyValue = ["","",""];
我觉得这个对象要int吗?[]。
Thnaks
sushil
我尝试过: ((IEnumerable)propertyValue).Cast
这将有效。现在好吗?
就个人而言,我不会那样做(但很接近):
That will work. Does it now?
Personally, I wouldn't do it quite like that (but close):
int?[] result = null;
var enumerable = propertyValue as IEnumerable;
// will be null if not IEnumerable. These checks are always valid
if(enumerable != null && enumerable.All(i=>i is int?) //or is INullable<int>. they should be the same
result = enumerable.Cast<int?>().ToArray()
return result;
这将返回一个int?[]或null。
就个人而言,我会添加抛出异常的检查,这样我就可以确定为什么我会得到null。毕竟,它可能是一个不同的对象,或者是一个null int?[]。
这不起作用null是int?总是等于false。
相反,替换为i => i == null ||我是int
这是通过的完整单元测试:
This will return either a int?[] or null.
Personally I would add checks that throw exceptions so I can identify why I'm getting null. After all, it might be a different object, or a null int?[].
This did not work as "null is int?" always equals false.
Instead, replace with "i=>i==null || i is int"
Here is the full unit test that passes:
[TestMethod]
public void TryPart1()
{
int?[] value = new int?[10];
for (int i = 0; i < value.Length; i++)
{
value[i] = (i > 4) ? (int?)null : 0;
}
object a = value;
var result = TryPart2(a);
Assert.IsTrue(result != null);
Assert.IsTrue(result.Length == 10);
}
public int?[] TryPart2(object a)
{
int?[] result = null;
var enumerable = a as IEnumerable;
if (enumerable != null)
{
var objects = enumerable.Cast<object>().ToArray();
if (objects.All(o => o==null || o is int))
result = objects.Cast<int?>().ToArray();
}
return result;
}
您需要这样做,我已经在我的机器上测试了这段代码:
You need to to do it something like this, i have tested this code on my machine:
using System;
using System.Linq;
using System.Collections.Generic;
public class HelloWorld
{
public static void Main()
{
int?[] NullableIntArray;
object value = new object[]{"a",0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
int result;
NullableIntArray = ((IEnumerable<object>)value)
.Select(x=>int.TryParse(x.ToString(),out result) ? (int?)result : (int?)null)
.ToArray();
}
}