【问题标题】:Create Generic Class Accepting T as an enum创建接受 T 作为枚举的通用类
【发布时间】:2020-01-19 10:00:49
【问题描述】:

我有这个类,我希望它接受一个泛型作为枚举 我可以在构造函数中传递它,但我想使用泛型。

这是我的界面:

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

我希望我的班级像这样

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
        //}
    }
}

但得到这个错误:

'TEnum' 不包含 'ToBaseUrl' 的定义和最好的 扩展方法重载'Extentions.ToBaseUrl(Company, string)' 需要“公司”类型的接收器

我该怎么做?

【问题讨论】:

  • 如果您正在寻找通用的enum 约束,请参阅Create Generic method constraining T to an Enum。但似乎Extentions.ToBaseUrl() 是枚举的特定类型 的扩展方法,特别是Company,所以在这里使用泛型是不明智的。
  • @dbc 你的意思是它不能完成?
  • 我不明白你想做什么。当实际上只允许一种特定的 enum 类型时,为什么要使该类通用? enum 是否保存在课堂的某个地方,即使它没有显示?您可以编辑您的问题以分享minimal reproducible example吗?
  • @dbc 我试图做的事情你在第一条评论中说过,所以你建议我应该使用构造函数
  • @alirezas 请与我们分享ToBaseUrl() 方法,它是如何声明的

标签: c# asp.net-mvc generics enums httpclient


【解决方案1】:

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();
        /* ... */
    }
}

【讨论】:

    猜你喜欢
    • 2010-09-09
    • 1970-01-01
    • 1970-01-01
    • 2021-03-17
    • 2013-08-22
    相关资源
    最近更新 更多