界面作为类型约束和界面作为参数的区别? [英] Difference between interface as type constraint and interface as parameter?
问题描述
如果我想创建一个将 IList
的实例作为参数(或任何其他接口,但让我们使用 IList code>作为例子),我可以创建一个类型约束的泛型方法,例如:
public static void Foo1< T>(T list)其中T:IList
{
}
或者,我可以创建一个直接使用 IList
参数的方法:
public static void Foo2(IList list)
{
}
对于所有的意图和目的,这些方法看起来像是完全一样:
List< string> ; myList = new List< string>();
Foo1(myList);
Foo2(myList);
这是我的问题 - 这两种方法有什么区别?看起来第二种方法更具可读性;是否还有其他差异我应该知道(不同的IL正在生成等)?
有几点不同:
T
可能是一个值类型,但最终仍然以通用形式取消装箱。对于 IList
这种情况是不太可能的,但对于其他接口而言,这很可能是
T
是
这实际上取决于你当然在做什么......除非你真的需要知道关于 T
,通用表单的唯一好处是装箱点。
If I wanted to create a method that takes an instance of IList
as a parameter (or any other interface, but let's use IList
as an example), I could create a generic method with a type constraint, e.g.:
public static void Foo1<T>(T list) where T : IList
{
}
Alternatively, I could create a method that takes an IList
parameter directly:
public static void Foo2(IList list)
{
}
For all intents and purposes, it seems like these methods behave exactly the same:
List<string> myList = new List<string>();
Foo1(myList);
Foo2(myList);
So here's my question -- what's the difference between these two approaches? It seems like the second approach is slightly more readable; are there any other differences I should be aware of (different IL being generated, etc)? Thanks in advance.
A couple of differences:
- If you ever need the real type again (e.g. to pass to another generic method or for logging) then the generic method will be better
T
could be a value type and still end up being unboxed in the generic form. It's pretty unlikely that this would be the case forIList
, but for other interfaces it's highly plausible- The generic form allows you to specify a concrete implementation type which is different from the actual object type. For example, you might pass in a null reference but still want to know which implementation type
T
is - They will be JITted differently; see Joe Duffy's recent blog post on generics for more information
It really depends on what you're doing of course... unless you actually need to know anything about T
within the method, the only benefit to the generic form is the boxing point.
这篇关于界面作为类型约束和界面作为参数的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!