问题描述
我有一个 C# 接口,其中某些方法参数声明为 object
类型.但是,传递的实际类型可能因实现接口的类而异:
I have a C# interface with certain method parameters declared as object
types. However, the actual type passed around can differ depending on the class implementing the interface:
public interface IMyInterface
{
void MyMethod(object arg);
}
public class MyClass1 : IMyInterface
{
public void MyMethod(object arg)
{
MyObject obj = (MyObject) arg;
// do something with obj...
}
}
public class MyClass2 : IMyInterface
{
public void MyMethod(object arg)
{
byte[] obj = (byte[]) arg;
// do something with obj...
}
}
MyClass2 的问题在于 byte[]
与 object
的转换是 装箱和拆箱,这是影响性能的计算成本高的操作.
The problem with MyClass2 is that the conversion of byte[]
to and from object
is boxing and unboxing, which are computationally expensive operations affecting performance.
会用 通用接口 解决这个问题,避免装箱/拆箱?
Would solving this problem with a generic interface avoid boxing/unboxing?
public interface IMyInterface<T>
{
void MyMethod(T arg);
}
public class MyClass1 : IMyInterface<MyObject>
{
public void MyMethod(MyObject arg)
{
// typecast no longer necessary
//MyObject obj = (MyObject) arg;
// do something with arg...
}
}
public class MyClass2 : IMyInterface<byte[]>
{
public void MyMethod(byte[] arg)
{
// typecast no longer necessary
//byte[] obj = (byte[]) arg;
// do something with arg...
}
}
这是如何在 .NET 与 Mono 中实现的?这两个平台都会对性能产生影响吗?
How is this implemented in .NET vs Mono? Will there be any performance implications on either platform?
谢谢!
推荐答案
我不确定它是如何在 mono 中实现的,但是泛型接口会有所帮助,因为编译器会为使用的每种不同类型创建一个特定类型的新函数(在内部,在少数情况下它可以利用相同的生成函数).如果生成了特定类型的函数,则无需对该类型进行装箱/拆箱.
I'm not sure how it is implemented in mono, but generic interfaces will help because the compiler creates a new function of the specific type for each different type used (internally, there are a few cases where it can utilize the same generated function). If a function of the specific type is generated, there is no need to box/unbox the type.
这就是 Collections.Generic 库在 .NET 2.0 中大受欢迎的原因,因为集合不再需要装箱并且变得更加高效.
This is why the Collections.Generic library was a big hit at .NET 2.0 because collections no longer required boxing and became significantly more efficient.
这篇关于C# 中的泛型接口会防止装箱吗?(.NET 与 Mono 性能)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!