简体   繁体   中英

Embed generic new() constraint into interface/class?

So far I've been adding new() constraint like this.

public T Request<T>(BaseRequest request)
        where T : BaseResponse, new()

Is there a way to bake the new() into BaseResponse so that I only need to specify

        where T : BaseResponse

No. A derived class can always have a private/protected constructor, and there's no way to prevent that. It might even be an abstract class.

The only exception are struct s, which always have a default constructor - the one you get with default(SomeStruct) . Needless to say, this simply means the struct is initialized with zeroes (though C# 6 made this a bit more complicated).

The only way you could spare some typing, provided you have several generic methods in your class, is to make the class generic instead, ie go from this:

class YourClass
{
    public static T Request<T>(BaseRequest request)
       where T : BaseResponse, new()
    { }

    public static T SomethingElse<T>(BaseRequest request)
       where T : BaseResponse, new()
    { }
}

to this:

class YourClass<T> where T : BaseResponse, new()
{
    public static T Request(BaseRequest request)
    { }

    public static T SomethingElse(BaseRequest request)
    { }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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