[英]Casting Using ArrayList Under .NET4.5
我所有的實用方法都定義為
public static Dictionary<T, int> CountOccurences<T>(IEnumerable<T> items) { ... }
我有一些遺留代碼,遺憾的是使用ArrayList
而不是List<T>
。 現在,我需要轉換ArrayList
以使用上面的方法,以下兩個都應該工作
var v = CountOccurences<String>(arrayList.Cast<String>().ToArray());
要么
var v = CountOccurences<String>(arrayList.OfType<String>().ToArray());
這些都不適用於.NET 4.5中的VS2012
'System.Collections.ArrayList'不包含'OfType'的定義,並且沒有可以找到接受類型'System.Collections.ArrayList'的第一個參數的擴展方法'OfType'(您是否缺少using指令或程序集引用?)
但是,我已經在LINQpad中對它進行了測試,它們都可以工作。 為什么我不能投射我的ArrayList
?
謝謝你的時間。
以下在VS2012中對我來說很好
ArrayList al = new ArrayList();
al.Add("a");
al.Add("b");
al.Add("c");
var v = al.OfType<string>().ToArray();
var list = new List<string>(v); //Constructor taking an IEnumerable<string>();
您收到了什么錯誤消息。
確保包含以下命名空間
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
我認為“不工作”意味着你得到一個InvalidCastException
。 因此,並非ArrayList
中的所有對象都是字符串。 你可以通過創建一個新的非泛型的CountOccurences
重載來CountOccurences
這個問題,它需要一個ArrayList
:
(假設方法的功能)
public static Dictionary<string, int> CountOccurences(ArrayList items)
{
var dict = new Dictionary<string, int>();
foreach(object t in items)
{
string key = "";
if(t != null)
key = t.ToString();
int count;
dict.TryGetValue(key, out count);
dict[key] = count++;
}
return dict;
}
在我的情況下不會拋出任何錯誤:
順便說一下,你對OfType<T>
是錯誤的。 這是一個方法,所以append ()
。
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _16853758
{
class Program
{
static void Main(string[] args)
{
ArrayList arrayList = new ArrayList();
var a = CountOccurences<String>(arrayList.Cast<String>().ToArray());
var v = CountOccurences<String>(arrayList.OfType<String>().ToArray());
}
public static Dictionary<T, int> CountOccurences<T>(IEnumerable<T> items) { return new Dictionary<T, int>(); }
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.