【问题标题】:How to apply == to generic types - data types like string or int in C#如何将 == 应用于泛型类型 - C# 中的字符串或 int 等数据类型
【发布时间】:2020-04-13 10:55:15
【问题描述】:

我有以下通用类:

public class Entity<Key>
{
    public Key ID;
}

public interface IEntity<T>
{
    T ID { get; set; }
}

public class GenericRepo<TEntity,CEntity,Key>
    where TEntity : class, IEntity<Key>
    where CEntity : class, IEntity<Key>
{
    protected readonly DataContext _context;
    protected readonly IMapper _mapper;

    public GenericRepo(DataContext context, IMapper mapper)
    {
        _context = context;
        _mapper = mapper;
    }

    public CEntity GetByID(Key id)
    {
        //here i get operators == cannot be applied to operands of type 'Key' and 'Key'
        TEntity dbEntity = _context.Set<TEntity>().FirstOrDefault(e => e.ID == id);

        if (dbEntity == null)
        {
            return null;
        }

        return _mapper.Map<CEntity>(dbEntity);
    }
}

我正在尝试将泛型类型 Key 传递给 ID 属性。当我在传递的参数上使用== 和同样属于Key 类型的Set 属性时,我得到operators == cannot be applied to operands of type 'Key' and 'Key',因为它们是相同的泛型类型Key,我如何在Key 上实现相等在这些课程上?

我需要传递的类型是intstring

但是,我尝试将where 子句添加到where T : Type 类中,操作数错误被删除,但现在我既不能传递string 也不能传递int,如下面的Entity&lt;int&gt; 我得到there is no boxing conversion from int to System.Type

我看到了一些答案,例如使用 .Equals 并将 IComparer 实现到类,但在我的情况下,它是一种类型,我需要 == 才能在 EF-core 的 LINQ to SQL 中使用它。

是否有任何where 条件可以添加到类中,我可以将类型传递给我的类并使用== 或任何其他方式?

【问题讨论】:

  • @WaiHaLee 我看到了,几乎所有答案都使用EqualityComparer,我希望找到一种方法通过stringint 并将它们与== 进行比较而无需通过IComparer 或类似接口
  • 这个link 可能对你有帮助

标签: c# generics linq-to-sql


【解决方案1】:

如何将 == 应用于泛型类型

你没有。可以说 .NET 类型系统的一个弱点是泛型无法处理操作,因为操作是通过静态方法定义的。

您几乎必须通过 IComparable 或类似的界面。

【讨论】:

    【解决方案2】:

    我最终使用了一个简单的.Equals()

    TDataSet dbEntity = _context.Set<TDataSet>().FirstOrDefault(e => e.ID.Equals(id));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-30
      • 2012-12-24
      • 1970-01-01
      • 2019-09-10
      • 1970-01-01
      相关资源
      最近更新 更多