[英]Implementing Interface to a Generic method parameter VS Implementing Interface to an method argument
Im quite confused by what i found in a programming course. 我对编程课程中的内容感到很困惑。
In brief - I found a method which has that construction: 简而言之 - 我发现了一种具有这种结构的方法:
public void MethodA<T>(T a) where T : IComparable
{
//...
}
And as far as i know - the same exact effect we can can achive using just this: 据我所知 - 我们可以使用相同的确切效果:
public void MethodB(IComparable a)
{
//...
}
Are those two ways differ from each other somehow and has one of them any advantage over the other? 这两种方式在某种程度上是否有所不同,并且其中一种方式优于另一种方式? If so, how could look a scenario where one of them is better to use? 如果是这样,那么如何才能看出其中一个更好用?
Thanks a lot! 非常感谢!
I was curious so I made a little testcode myself: 我好奇,所以我自己做了一个小测试代码:
public interface ITest
{
int Value { get; set; }
}
public struct TestStruct : ITest
{
public int Value { get; set; }
}
private static void TestMethodGeneric<T>(T value) where T : ITest
{
}
private static void TestMethodNonGeneric(ITest value)
{
}
And in my main method I use both calls: 在我的主要方法中,我使用两个调用:
TestStruct ts = new TestStruct {Value = 10};
TestMethodNonGeneric(ts);
TestMethodGeneric(ts);
And this is the resulting IL code: 这是由此产生的IL代码:
Non-generic: 非通用:
IL_0031: ldloc.0 // ts
IL_0032: box Tests.Program/*02000002*//TestStruct/*02000026*/
IL_0037: call void Tests.Program/*02000002*/::TestMethodNonGeneric(class Tests.Program/*02000002*//ITest/*02000025*/)/*06000002*/
IL_003c: nop
Generic: 通用:
IL_0059: ldloc.0 // ts
IL_005a: call void Tests.Program/*02000002*/::TestMethodGeneric<valuetype Tests.Program/*02000002*//TestStruct/*02000026*/>(!!0/*valuetype Tests.Program*//*02000002*//*/TestStruct*//*02000026*//**/)/*06000001*/
IL_005f: nop
So you see, in the generic version, the specific type is used and therefor no boxing occurs. 所以你看,在通用版本中,使用了特定的类型,因此没有发生装箱。
In the non-generic version, the struct
value has to be casted to ITest
and so it gets boxed. 在非泛型版本中, struct
值必须被转换为ITest
,因此它被装箱。 So the generic version has a (very tiny) performance advantage. 因此,通用版本具有(非常小的)性能优势。
Just my two cents, there maybe other more or less important differences in the two approaches. 只是我的两分钱,这两种方法可能存在其他或多或少的重要差异。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.