在方法重载通用约束上 [英] Generic contraints on method overloads
问题描述
我有一些通用的方法的接口,我想用重载来实现的方法是接受一个类的实例,或它的PK值(或者是一个int或GUID但有所不同)。
I've got an interface with some generic methods, and I wanted to implement a method with overloads to either accept an instance of a class, or its PK value (which is either an int or GUID but does vary).
我添加类似于这些例子方法:
I added to methods similar to these examples:
void DoSomething<TKey>(TKey key) where TKey: struct;
void DoSomething<TModel>(TModel model) where TModel : class;
在这第二个的DoSomething的方法名被突出显示,且误差
The 'DoSomething' method name on the second of these is highlighted, and the error is
键入ISomeStuff'已经定义了一个名为DoSomething的与
相同的参数类型的成员。
Type 'ISomeStuff' already defines a member called 'DoSomething' with the same parameter types.
我对这个感到惊讶,因为我已经明确的参数定义为不同的类型:一种是类,另一个是结构。
I'm surprised by this as I've clearly defined by parameters to be of different type: one is a class and the other a struct.
为什么不这样不足以使签名不同?
Why isn't this sufficient to make the signatures different?
推荐答案
乔恩斯基特有一个一切问题的答案:的点击我
Jon Skeet has an answer to everything: click me
报价:
的声明只是不同在一般的约束和限制
不签名
the declarations only differ in generic constraints, and constraints aren't part of the signature
这篇关于在方法重载通用约束上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!