gpt4 book ai didi

c# - 方法参数 : Interface VS Generic type

转载 作者:太空狗 更新时间:2023-10-29 21:28:02 24 4
gpt4 key购买 nike

使用这两个方法实现中的一个或另一个的参数是什么(在 Example 类中)?

public interface IInterface
{
void DoIt();
}

public class Example
{
public void MethodInterface(IInterface arg)
{
arg.DoIt();
}

public void MethodGeneric<T>(T arg) where T: IInterface
{
arg.DoIt();
}
}

PS:如果方法返回 IInterfaceT 我会选择“通用”方式以避免在需要时进一步转换类型 T .

最佳答案

两者看似相同,但实际上不同。

通用版本在传递时不会对 ValueType 进行装箱,因为非通用版本需要“装箱”

这是一个小示例程序和相关的 IL,它演示了这种情况

void Main()
{
Example ex = new Example();
TestStruct tex = new TestStruct();
ex.MethodGeneric(tex);
ex.MethodInterface(tex);
}
public interface IInterface
{
void DoIt();
}

public class Example
{
public void MethodInterface(IInterface arg)
{
arg.DoIt();
}

public void MethodGeneric<T>(T arg) where T : IInterface
{
arg.DoIt();
}
}

internal struct TestStruct : IInterface
{
public void DoIt()
{

}
}

下面是生成的IL的相关部分

IL_0001:  newobj      UserQuery+Example..ctor
IL_0006: stloc.0 // ex
IL_0007: ldloca.s 01 // tex
IL_0009: initobj UserQuery.TestStruct
IL_000F: ldloc.0 // ex
IL_0010: ldloc.1 // tex
IL_0011: callvirt UserQuery+Example.MethodGeneric
IL_0016: nop
IL_0017: ldloc.0 // ex
IL_0018: ldloc.1 // tex
IL_0019: box UserQuery.TestStruct //<--Box opcode
IL_001E: callvirt UserQuery+Example.MethodInterface

虽然这是一个偏好问题,但 MethodGeneric 是在“ValueTypes”情况下表现更好的方法

关于c# - 方法参数 : Interface VS Generic type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19950673/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com