简体   繁体   English

从参数推断通用类型

[英]Infer generic type from argument

Is there any way to infere the type parameter dynamically so that the type of an object is used as another objects type? 有什么方法可以动态推断类型参数,以便将一个对象的类型用作另一个对象类型?

I have a generic type called ObjectPrinter that takes a list of the same type it is of in the constructor. 我有一个称为ObjectPrinter的泛型类型,该类型具有与构造函数中相同类型的列表。 It would be neat to not have to declare the type but just have it infered from the argument. 不必声明类型,而只是从参数中推断出类型,将是很不错的选择。

        // 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

Constructors in C# are explicitly not generics - you can't do what you want to do directly. C#中的构造函数显然不是泛型-您无法直接执行您想做的事情。 Only member functions can have generic parameters. 只有成员函数可以具有通用参数。

However, that tells you what you can do: use a factory function instead of a constructor. 但是,这告诉您您可以做什么:使用工厂函数而不是构造函数。 Something like this: 像这样:

public class PrinterFactory {

    public static ObjectPrinter CreatePrinter<T>(List<T> things) {
        return new ObjectPrinter<T>(things);
    }
}

Then you can change your calling code to: 然后,您可以将调用代码更改为:

List<Fruit> myFruits = GetFruits();
var fruitPrinter = PrinterFactory.CreatePrinter(myFruits);

And everything should just work. 一切都应该工作。

You can of course put the factory function on whatever class you want. 当然,您可以将工厂函数放在所需的任何类上。

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

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