简体   繁体   中英

Casting Using ArrayList Under .NET4.5

All I have a utility method that is defined as

public static Dictionary<T, int> CountOccurences<T>(IEnumerable<T> items) { ... }

I have some legacy code that unfortunately uses ArrayList s instead of List<T> . Now, I need to cast the ArrayList to use the above method and both of the following should work

var v = CountOccurences<String>(arrayList.Cast<String>().ToArray());

or

var v = CountOccurences<String>(arrayList.OfType<String>().ToArray());

Neither of these work in VS2012 under .NET 4.5 giving

'System.Collections.ArrayList' does not contain a definition for 'OfType' and no extension method 'OfType' accepting a first argument of type 'System.Collections.ArrayList' could be found (are you missing a using directive or an assembly reference?)

However, I have tested this in LINQpad and they both work. Why can't I cast my ArrayList ?

Thanks for your time.

The following works fine for me in 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>();

What error message are you receiving.

Make sure you are including the following namespaces

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

I assume that "not work" means that you get an InvalidCastException . So not all objects in the ArrayList are strings. You could circumvent the problem by creating a new non-generic overload of CountOccurences which takes an ArrayList :

(presuming the functionality of the method)

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;
}

Doesn't throw any errors in my case:

BTW, your usage of OfType<T> is wrong. It's a method, so 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>(); }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM