开发者

Can .NET implicitly find out one type parameter from another?

We've got a base class for most of our domain object:

public class AbstractEntity<TKey>
{
    public virtual TKey ID { get; set; }
}

Now, for example, I've got class MobileOperator : AbstractEntity<int>.

What I want to do is to write generic equality comparer for all AbstractEntity descendants. And I want to create it like that:

var comparer = new AbstractEntityComparer<MobileOperator>();

I declare this comparer as following:

public class AbstractEntityEqualityComparer<TAbstractEntity, TId> : IEqualityComparer<TAbstractEntity>
    where TAbstractEntity : AbstractEntity<TId>

However, in this case I must explicitly tell the compiler that TId = int: new AbstractEntityComparer<MobileOperator, int>(). And if I put, say, long instead of int, it just wont compile. So, definitely, the compiler has a way to determine which type I use to create MobileOperator.

So is it possible to write comparer in a way that won't make me write this redu开发者_JAVA技巧ndant int thing all the time? And if yes, how can I do it?


C# doesn't do type inference based on constraints, so you need the explicit generic construction. See the this blog post by Eric Lippert for the details (and also an argument in the comments about why he's wrong wrong wrong.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜