簡體   English   中英

方法參數:接口VS通用類型

[英]Method parameter: Interface VS Generic type

使用這兩個方法實現中的一個或另一個的參數是什么(在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”的情況下表現更好的那個

我建議將Interface作為一個簡單的參數傳遞,而不是使用通用方法,原因如下:

  1. 設計更簡單,可實現更好的可維護性
  2. 更易讀的代碼,更少的專業知識
  3. 更好地支持依賴注入和IoC
  4. 沒有反思(我不確定這一點,我將提供證據,因為泛型使用反射來理解類型)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM