本文介绍了如何为泛型提供默认类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类,当前有一些采用整数参数的方法。这些整数映射到应用程序可以执行的操作。我想使该类具有通用性,以便该类的使用者可以提供他们具有的所有操作类型的枚举类型,然后这些方法将采用该枚举类型的参数。但是,我希望他们完全不指定泛型,而将其默认设置为整数,并且语法与当前方式相同。

I have a class that currently has several methods that take integer parameters. These integers map to operations that the application can perform. I'd like to make the class generic so that the consumers of the class can provide an enum type that they have with all the operations in it, then the methods will take parameters of that enum type. However, I want them to be able to not specify a generic type at all, and have it default back to integers with no change in syntax from the current way. Is this possible?

推荐答案

您不能在类的定义中做到这一点:

You can't do it in the definition of the class:

var foo = new MyGenericClass(); // defaults to integer... this doesn't work
var bar = new MyGenericClass<MyEnum>(); // T is a MyEnum

如果真正重视默认类型int的隐式性,您将

If really value the implicitness of the default type being int, you'll have to do it with a static factory method, although I don't see the value of it.

public class MyGenericClass<T>
{
    public static MyGenericClass<T> Create()
    {
        return new MyGenericClass<T>();
    }
    public static MyGenericClass<int> CreateDefault()
    {
        return new MyGenericClass<int>();
    }
}

请参阅下面的内容,了解如何从中真正受益

See below for how you really don't benefit from the above.

var foo = MyGenericClass<MyEnum>.Create();
var bar1 = MyGenericClass.CreateDefault(); // doesn't work
var bar2 = MyGenericClass<int>.CreateDefault(); // works, but what's the point

有什么意义呢?如果您想更进一步,可以创建一个静态工厂类可以解决此问题,但是如果您出于其他原因(提供默认类型)这样做,那将是一个更加荒谬的解决方案:

If you want to take it even farther, you can create a static factory class that will solve this, but that's an even more ridiculous solution if you're doing it for no other reason than to provide a default type:

public static class MyGenericClassFactory
{
    public static MyGenericClass<T> Create<T>()
    {
        return new MyGenericClass<T>();
    }
    public static MyGenericClass<int> Create()
    {
        return new MyGenericClass<int>();
    }
}

var foo = MyGenericClassFactory.Create(); // now we have an int definition
var bar = MyGenericClassFactory.Create<MyEnum>();

这篇关于如何为泛型提供默认类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 03:56