明确实现的接口和通用约束 [英] Explicitly implemented interface and generic constraint
本文介绍了明确实现的接口和通用约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
interface IBar {void Hidden(); }
$ b $ class Foo:IBar {public void Visible(){/*...*/} void IBar.Hidden(){/*...*/}}
class Program
{
static T CallHidden1< T>(T foo)其中T:Foo
{
foo.Visible();
((IBar)foo).Hidden(); //投射需要
返回foo;
static T CallHidden2< T>(T foo)其中T:Foo,IBar
{
foo.Visible();
foo.Hidden(); // OK
return foo;
$ b 是否有区别(CallHidden1与CallHidden2)是实际编译的代码?
在T:Foo和T:Foo,IBar(如果Foo实现IBar)的地方,在访问显式实现的接口成员之间还有其他区别吗?
解决方案生成的IL略有不同:
L_000d:ldarg.0
L_000e :box !! T
L_0013:callvirt实例void WindowsFormsApplication1.IBar :: Hidden()
vs。
L_000d:ldarga.s foo
L_000f:约束!! T
L_0015:callvirt如果 T $> c $ c>是一个值类型,这会导致在 CallHidden1
中装入 foo
,但不会在 CallHidden2
。但是,由于 Foo
是一个类,所以从 Foo $ c派生的任何类型 T
$ c>不会是值类型,因此行为将是相同的。
interface IBar { void Hidden(); }
class Foo : IBar { public void Visible() { /*...*/ } void IBar.Hidden() { /*...*/ } }
class Program
{
static T CallHidden1<T>(T foo) where T : Foo
{
foo.Visible();
((IBar)foo).Hidden(); //Cast required
return foo;
}
static T CallHidden2<T>(T foo) where T : Foo, IBar
{
foo.Visible();
foo.Hidden(); //OK
return foo;
}
}
Is there any difference (CallHidden1 vs. CallHidden2) is actual compiled code?
Is there other differences between where T : Foo and where T : Foo, IBar (if Foo implements IBar) that in accessing explicitly implemented interface members ?
解决方案 The IL generated is slightly different:
L_000d: ldarg.0
L_000e: box !!T
L_0013: callvirt instance void WindowsFormsApplication1.IBar::Hidden()
vs.
L_000d: ldarga.s foo
L_000f: constrained !!T
L_0015: callvirt instance void WindowsFormsApplication1.IBar::Hidden()
If T
were a value type, this would result in foo
being boxed in CallHidden1
but not in CallHidden2
. However, since Foo
is a class, any type T
derived from Foo
will not be a value type, and thus the behavior will be identical.
这篇关于明确实现的接口和通用约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文