How to allow a method to accept two data types as an argument?

I have a method that accepts a Hashtable (yes, I know, it's deprecated ..) as an argument:

public static LuaTable HashtableToLuatable(Hashtable t, int depth = 1)

This is working correctly.

Now I would like to accept ArrayList as the first parameter, so you can let 't' have a value of both Hashtable and ArrayList. Currently, I have copied the method twice, for example:

public static LuaTable ArraylistToLuatable(ArrayList t, int depth = 1)

The rest is exactly the same.

I think there is a way to merge this.

+1
source share
6 answers

Both classes implement the ICollection interface, so if your "common code" works against the definition of the ICollection interface, you can use it for your parameter type.

+10
source

, , , #.

, . "". , .

ArrayList : IList, ICollection, IEnumerable

Hashtable : IDictionary, ICollection, IEnumerable

, , :

public static LuaTable HashtableToLuatable(ICollection t, int depth = 1)

ICollection,

public static LuaTable HashtableToLuatable(IEnumerable t, int depth = 1)

IEnumerable, ICollection, IEnumerable ( ) .

+2

IEnumerable ICollection, , :

public static LuaTable EnumerableToLuaTable(IEnumerable t, int depth = 1)

public static LuaTable CollectionToLuaTable(ICollection t, int depth = 1)

IEnumerable ICollection, ICollection.

+2

( ) : IEnumerable ICollection. , , .

static void ArraylistToLuatable<T>( T collection ) where T : IEnumerable
{
    foreach( var item in collection )
    {
        // do something
    }
}

, , item object, ArrayList, HashTable, a DictionaryEntry - , , item.

, ? , DLL? , , . , , , .

+1

, / , ICollection, :

public static LuaTable HashtableToLuatable(ICollection t, int depth = 1) {

    if(t is ArrayList)
    {
        var collection = (ArrayList)t;
        // work with t as an ArrayList
    }
    else if (t is Hashtable)
    {
        var collection = (HashTable)t;
        // work with t as a HashTable
    }

}
0

, .

public static LuaTable <T> HashtableToLuatable(T t, int depth = 1) where T : ICollection

, .

0

All Articles