如何将==应用于通用类型-数据类型,例如C#中的字符串或整数

问题描述 投票:0回答:2

我有以下通用类:

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属性。当我在传递的参数和Set的属性(也为operators == cannot be applied to operands of type 'Key' and 'Key'类型)上使用==时得到Key,因为它们是相同的通用类型Key,如何在Key上实现相等性在这些课程上?

我需要传递的类型是intstring

但是,我尝试向类where中添加where T : Type子句,消除了操作数错误,但是现在我无法像下面的string一样传递intEntity<int>,但我无法获得there is no boxing conversion from int to System.Type。] >

[我看到了一些使用类.Equals并将IComparer实现到类的答案,但就我而言,它是一种类型,我需要==在ef-core的LINQ to SQL中使用它。

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

我有以下通用类:公共类实体{公共密钥ID; }公共接口IEntity {T ID {get;组; }}公共类GenericRepo [

c# generics linq-to-sql
2个回答
1
投票
如果e.ID具有Key类型(与id参数相同,则应该工作。

还有一个旁注,泛型类型参数通常以大写字母T开头,最好声明TKey而不是Key。它使您可以区分常规类型参数和泛型参数


0
投票
您没有。可以说.NET类型系统是一个弱点,因为操作是通过静态方法定义的,泛型无法处理操作。
您几乎必须通过IComparable或类似的界面。
© www.soinside.com 2019 - 2024. All rights reserved.