我正在尝试创建一个基于给定泛型类型从数据库返回数据的方法。
接口:(此定义编译)
public interface IOrderPosition<TOrder, TArticle, TOrderPosition>
where TOrder : IOrder
where TArtile : IArticle
where TOrderPosition : IOrderPosition<TOrder, TArticle, TOrderPosition>
{
long? id { get; set; }
TOrder order { get; set; }
TArtile article { get; set; }
List<TOrderPosition> subPositions { get; set; }
}
一个可能的具体实现:(这个定义编译)
public class OrderPosition : IOrderPosition<Order, Article, OrderPosition>
{
public long? id { get; set; }
public Order order { get; set; }
public Article article { get; set; }
public List<OrderPosition> subPositions { get; set; }
}
尝试基于接口编写通用方法:(此定义不编译)
public List<TOrderPosition> GetOrderPositionOfOrder<TOrderPosition>(long? id)
where TOrder : IOrder
where TArticle : IArticle
where TOrderPosition : IOrderPosition<TOrder, TArticle, TOrderPosition>
{
..
}
错误:
'DataSourceOrder.GetOrderPositionOfOrder<TOrderPosition>()' does not define type parameter 'TOrder'
'DataSourceOrder.GetOrderPositionOfOrder<TOrderPosition>()' does not define type parameter 'TArticle'
The type or namespace name 'TOrder' could not be found (are you missing a using directive or an assembly reference?)
The type or namespace name 'TArticle' could not be found (are you missing a using directive or an assembly reference?)
像这样使用:
List<OrderPosition> positions = GetOrderPositionOfOrder<OrderPosition>(5);
List<TransferOrderPosition> transferPositions = GetOrderPositionOfOrder<TransferOrderPosition>(5);
问题:
为什么这会为接口编译,而不是为方法编译?
我希望两者都能工作或都失败。我假设编译器可以从给定的 TOrderPosition 类型推断出 TOrder 和 TArticle 的类型,该类型定义了文章和订单的具体类型。
我想知道为什么会发生这种情况以及是否以及如何解决问题而无需明确指定所有类型。