C# 从参数推断泛型类型

C# 从参数推断泛型类型,c#,generics,C#,Generics,是否有任何方法可以动态推断类型参数,以便将对象的类型用作另一个对象类型 我有一个名为ObjectPrinter的泛型类型,它接受与构造函数中相同类型的列表。不必声明类型,而只需从参数中推断类型,这将是一件好事 // This is how i do it. But since myFruits is a list of fruits could not the type Fruit be infered automatically? List<Fruits&

是否有任何方法可以动态推断类型参数,以便将对象的类型用作另一个对象类型

我有一个名为ObjectPrinter的泛型类型,它接受与构造函数中相同类型的列表。不必声明类型,而只需从参数中推断类型,这将是一件好事

        // This is how i do it. But since myFruits is a list of fruits could not the type Fruit be infered automatically?
        List<Fruits> myFruits = GetFruits();
        var fruitPrinter = new ObjectPrinter<Fruit>(myFruits);

        // Id like to to this   
        List<Fruits> myFruits = GetFruits();
        var fruitPrinter = new ObjectPrinter(myFruits); // and get a ObjectPRinter of type Fruit
//我就是这样做的。但是,既然myFruits是一个水果列表,那么不能自动推断出水果的类型吗?
List myFruits=GetFruits();
var fruitPrinter=新对象打印机(myFruits);
//我想谈谈这个
List myFruits=GetFruits();
var fruitPrinter=新对象打印机(myFruits);//然后得到一个水果类型的ObjectPRinter
C#中的构造函数显然不是泛型-你不能直接做你想做的事情。只有成员函数才能具有泛型参数

但是,这告诉您可以做什么:使用工厂函数而不是构造函数。大概是这样的:

public class PrinterFactory {

    public static ObjectPrinter CreatePrinter<T>(List<T> things) {
        return new ObjectPrinter<T>(things);
    }
}
公共类PrinterFactory{
公共静态ObjectPrinter CreatePrinter(列出内容){
归还新的ObjectPrinter(物品);
}
}
然后,您可以将呼叫代码更改为:

List<Fruit> myFruits = GetFruits();
var fruitPrinter = PrinterFactory.CreatePrinter(myFruits);
List myFruits=GetFruits();
var fruitPrinter=PrinterFactory.CreatePrinter(myFruits);
一切都应该正常

当然,您可以将工厂函数放在您想要的任何类上