简体   繁体   English

创建接受 T 作为枚举的泛型类

[英]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' “TEnum”不包含“ToBaseUrl”的定义,最佳扩展方法重载“Extentions.ToBaseUrl(Company, string)”需要“Company”类型的接收器

How can I do that?我怎样才能做到这一点?

The System.Enum constraint is available starting from C# 7.3. System.Enum约束从 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();
        /* ... */
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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