Working around lack of partial generic type inference with constraints

前端 未结 1 1415
难免孤独
难免孤独 2020-12-20 13:32

I have an interface (which is used by repositories) that has this member:

T FindById(TId id)
    where T : class, IEntity
    where          


        
相关标签:
1条回答
  • 2020-12-20 14:09

    That can't work the usual way around because you can't convince the compiler of the TId constraint after the fact. You can, however, reverse the sequence, i.e.

    var obj = ById(id).Find<SomeType>();
    

    Not as elegant, but it works. Implementation:

    public Finder<TId> ById<TId>(TId id) where TId : IEquatable<TId>
    {
        return new Finder<TId>(this, id);
    }
    public struct Finder<TId> where TId : IEquatable<TId>
    {
        private readonly YourParent parent;
        private readonly TId id;
        internal Finder(YourParent parent, TId id)
        {
            this.id = id;
            this.parent = parent;
        }
        public T Find<T>() where T : class, IEntity<TId>
        {
            return parent.FindById<T, TId>(id);
        }
    }
    

    caveat: it is probably easier just to tell it both the parameter types explicitly.

    0 讨论(0)
提交回复
热议问题