猿问

如何动态转换对象[]中的项目?

我想找到一种方法来动态转换 object[] 元素并找到字符串“needle”我的问题来自第一个数组案例


  var haystack_1 = new object[]{'3', "123124234", null, "needle", "world", "hay", 2, '3', true, false};

  var haystack_2 = new object[]{"283497238987234", "a dog", "a cat", "some random junk", "a piece of hay", "needle", "something somebody lost a while ago"};

  var haystack_3 = new object[]{1,2,3,4,5,6,7,8,8,7,5,4,3,4,5,6,67,5,5,3,3,4,2,34,234,23,4,234,324,324,"needle",1,2,3,4,5,5,6,5,4,32,3,45,54};


   var index =  Array.FindIndex(haystack_1,item => item.ToString().Equals("needle"));

    Console.WriteLine(index);

错误


运行时异常(第 13 行):未将对象引用设置为对象的实例。


堆栈跟踪:


[System.NullReferenceException: Object reference not set to an instance of an object.] at Program.b__0(Object item):line 13 at System.Array.FindIndex[T](T[] array, Int32 startIndex, Int32 count, Predicate 1 match)    at System.Array.FindIndex[T](T[] array,

  Predicate1 匹配)在 Program.Main() :第 13 行


拉莫斯之舞
浏览 126回答 2
2回答

慕虎7371278

发生该错误是因为您试图ToString从null对象中获取。您可以使用为您Convert.ToString处理null对象的方法。主要区别是ToString()不能处理null而 Convert.ToString()可以处理空值。var index = Array.FindIndex(haystack_1, item => Convert.ToString(item).Equals("needle"));
随时随地看视频慕课网APP
我要回答