12

我有一个具有此成员的接口(由存储库使用):

T FindById<T, TId>(TId id)
    where T : class, IEntity<TId>
    where TId : IEquatable<TId>;

这允许调用者指定实体类型 ( T) 及其Id字段的类型 ( TId)。然后,此接口的实现者将找到类型的实体T并使用id参数根据它们的 id(在 上定义IEntity<TId>)过滤它们。

目前我这样称呼它:

int id = 123;
var myApproval = PartsDC.FindById<Approval, int>(id);

理想情况下,我想这样做:

int id = 123;
var myApproval = PartsDC.FindById<Approval>(id);

我已经阅读了这个问题的答案:

C# 中可能的部分泛型类型推断?

我知道我无法获得我想要的语法,但可以接近。由于我的通用参数限制,我无法完全正确地设置它。

这是我到目前为止所拥有的:

public class FindIdWrapper<T> where T : class
{
    public readonly IDataContext InvokeOn;

    public FindIdWrapper(IDataContext invokeOn)
    {
        InvokeOn = invokeOn;
    }

    T ById<TId>(TId id) where TId : IEquatable<TId>
    {
        return InvokeOn.FindById<T, TId>(id);
    }
}

public static class DataContextExtensions
{
    public static FindIdWrapper<T> Find<T>(this IDataContext dataContext) where T : class, IEntity
    {
        return new FindIdWrapper<T>(dataContext);
    }
}

我得到的编译错误是:

The type 'T' cannot be used as type parameter 'T' in the generic type or method 'PartsLegislation.Repository.IDataContext.FindById<T,TId>(TId)'. There is no implicit reference conversion from 'T' to 'PartsLegislation.Repository.IEntity<TId>'.

我明白它在说什么,因为T我的包装类中的 仅被限制为引用类型,但FindById函数希望它是IEntity<TId>,但我不能像TId方法中那样那样做(否则我回到第一方)。

我怎样才能解决这个问题(或者我不能)?

4

1 回答 1

7

TId这不能以通常的方式工作,因为事后您无法说服编译器接受约束。但是,您可以颠倒顺序,即

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

不那么优雅,但它有效。执行:

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);
    }
}

警告:明确地告诉它两种参数类型可能更容易。

于 2013-05-10T10:08:58.013 回答