繁体   English   中英

如何制作采用泛型类型的泛型方法

[英]How to make a generic method that take a generic type

我想写下面的方法

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

其中T必须是以TItem作为其通用信息的泛型类型。

调用示例如下:

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

编辑:在我的情况下,我只需要收集。 实际的用例是我想编写一个方法,向ICollection添加一些东西,遗憾的是ICollection没有.Add方法只有ICollection<T>有它。

我无法将方法更改为:

private Foo<T>(ICollection<T>)

因为我失去了信息实际列表的类型,这对我来说比列表中的项目类型更重要。

所以上述想法诞生了,但没有奏效。

由于您只需要集合,您可以描述这样的方法:

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

但是在这种情况下,您需要提供特定的泛型类型( List<int> )作为第一个泛型参数,您不能只使用List

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

也许这可以帮助:

创建基类和派生类。

public class Item
{

}

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

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

然后,您可以按照以下方式使用它:

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

在我看来,就像你陷入了一个心灵陷阱。 可能有更好的方法来解决你想做的事情。

无论如何,尝试使用Dictionary 您不需要实际编写方法。

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

最终,你的前瞻性代码注入大脑会放弃试图强化C#的强类型系统。 我们都在某个时候这样做。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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