How do you provide a default type for generics?

后端 未结 6 1537
醉梦人生
醉梦人生 2020-12-30 18:58

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 clas

6条回答
  •  一向
    一向 (楼主)
    2020-12-30 19:41

    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(); // T is a MyEnum
    

    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
    {
        public static MyGenericClass Create()
        {
            return new MyGenericClass();
        }
        public static MyGenericClass CreateDefault()
        {
            return new MyGenericClass();
        }
    }
    

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

    var foo = MyGenericClass.Create();
    var bar1 = MyGenericClass.CreateDefault(); // doesn't work
    var bar2 = MyGenericClass.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 Create()
        {
            return new MyGenericClass();
        }
        public static MyGenericClass Create()
        {
            return new MyGenericClass();
        }
    }
    
    var foo = MyGenericClassFactory.Create(); // now we have an int definition
    var bar = MyGenericClassFactory.Create();
    

提交回复
热议问题