简体   繁体   中英

How to make a generic method that take a generic type

I would like to write the following method

private void Foo<T, TItem>(T<TItem> param1)

Where T must be a generic type that takes TItem as its generic info.

Call example would be like:

private void Main()
{
    List<int> ints = new List<int>();
    Foo<List, int>(ints);    
}

Edit: In my case I would only need to for collections. The actual use case is that I wanted to write a method that adds something to a ICollection sadly the ICollection doesn't have an .Add method only the ICollection<T> has it.

I cannot change the method to:

private Foo<T>(ICollection<T>)

since with that I am losing the information what type the actual list is, which is more important to me than what type the items within the list.

so the above idea was born, which didn't work.

Since you need that for collections only, you could describe a method like this:

private void Foo<T, TItem>(T param1)
    where T: ICollection<TItem>
{
}

However in this case you need to provide specific generic type ( List<int> ) as first generic parameter, you can't use just List :

List<int> ints = new List<int>();
Foo<List<int>, int>(ints); 

Maybe this can help:

Create a base class and derived class.

public class Item
{

}

public class Item<T> : Item
{
    T Value;

    public Item(T value)
    {
        Value = value;
    }
}

You can then use it how you want to:

public class SomewhereElse
{
    public void Main()
    {
        List<Item> itemCollection = new List<Item>();
        itemCollection.Add(new Item<int>(15));
        itemCollection.Add(new Item<string>("text"));
        itemCollection.Add(new Item<Type>(typeof(Image)));
        itemCollection.Add(new Item<Exception>(new StackOverflowException()));
        itemCollection.Add(new Item<FormWindowState>(FormWindowState.Maximized));
        // You get the point..
    }
}

Seems to me like you are caught in a mind trap. There is probably a better way to solve whatever it is you are trying to do.

Anyway, try using a Dictionary . You don't need to actually write a method.

int number = 15;
double dub = 15.5;
Button button = new Button();

Dictionary<object, Type> typeGlossary = new Dictionary<object, Type>();
typeGlossary.Add(number, typeof(int));
typeGlossary.Add(dub, typeof(double));
typeGlossary.Add(button, typeof(Button));

Eventually, your forward raging code-injected brain will give up trying to un-strong the strongly typed system of C#. We all do it at some point.

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