开发者

Is it possible to define a default generic type?

开发者 https://www.devze.com 2022-12-11 09:25 出处:网络
public class StuffDoer<T> { // do stuff } I want that this is always of type string, so instead of doing this:
public class StuffDoer<T>
{
    // do stuff
}

I want that this is always of type string, so instead of doing this:

StuffD开发者_StackOverflow中文版oer<string> stuffer = new StuffDoer<string>();

I want to be able to do this:

StuffDoer stuffer = new StuffDoer();

and if I need a StuffDoer of type int, just define that with generics.

StuffDoer<int> stuffer = new StuffDoer<int>();

Is this possible?


Rather than using subclasses where there's no real specialization going on, I would suggest using a separate static "factory" class:

public static class StuffDoer
{
    public static StuffDoer<string> Create()
    {
        return new StuffDoer<string>();
    }

    public static StuffDoer<T> Create<T>()
    {
        return new StuffDoer<T>();
    }


    public static StuffDoer<T> Create<T>(T item)
    {
        StuffDoer<T> ret = new StuffDoer<T>();
        ret.Add(item); // Or whatever
        return ret;
    }
}

The last method lets you use type inference as well:

StuffDoer<int> doer = StuffDoer.Create(10);

This doesn't let you write new StuffDoer() admittedly - but I think it's a cleaner solution. Creating a non-generic derived class just as a sort of "type alias" feels like an abuse of inheritance to me.


You can just setup a plain StuffDoer class that inherits from StuffDoer<T>:

public class StuffDoer : StuffDoer<string>
{
    // ...
}

public class StuffDoer<T>
{
    // ...
}


public class StuffDoer<T>
{
    // do stuff
}

public class StuffDoer : StuffDoer<string>
{
    // do stuff
}
0

精彩评论

暂无评论...
验证码 换一张
取 消