简体   繁体   中英

Create Generic Class Accepting T as an enum

I have this class and i want that to accept a generic as an enum I can pas it in the constructor but I want to use generic.

this is my interface:

public interface ITrnApi<TEnum> : IDisposable where TEnum : struct

and I want my class to be like this one

public class TrnApi<TEnum> : ITrnApi<TEnum> where TEnum : struct
{
    private readonly HttpClient _http;

    public TrnApi(HttpClient http, TEnum company)
    {
        _http = http;
        _http.BaseAddress = company.ToBaseUrl().ToUri();

        //public enum Company
        //{
        //    test = 1,
        //    othertest = 2
        //}
    }
}

but get this error:

'TEnum' does not contain a definition for 'ToBaseUrl' and the best extension method overload 'Extentions.ToBaseUrl(Company, string)' requires a receiver of type 'Company'

How can I do that?

The System.Enum constraint is available starting from C# 7.3.

public class TrnApi<TEnum> : ITrnApi<TEnum> where TEnum : struct, Enum
{
    private readonly HttpClient _http;

    public TrnApi(HttpClient http, TEnum company)
    {
        _http = http;
        _http.BaseAddress = company.ToBaseUrl().ToUri();
        /* ... */
    }
}

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