2016-11-16 58 views
7

我寫的代碼:爲什麼C#編譯器產生的錯誤,即使使用屬性 「SpecialName」

using System.Runtime.CompilerServices; 

namespace ConsoleApplication21 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      int i = new MyClass1() - new MyClass1(); 
      int j = new MyClass1() + new MyClass1(); 
     } 
    } 

    public class MyClass1 
    { 
     public static int operator -(MyClass1 i, MyClass1 j) 
     { 
      return 5; 
     } 

     [SpecialName] 
     public static int op_Addition(MyClass1 i, MyClass1 j) 
     { 
      return 5; 
     } 
    } 
} 

編譯時錯誤:

Error 1 Operator '+' cannot be applied to operands of type 'ConsoleApplication21.MyClass1' and 'ConsoleApplication21.MyClass1'

因此,C#編譯器不喜歡行「INT J =新的MyClass1()+新的MyClass1();「 當我打開ILDASM,我得到了運營商超載的同一代碼:

Method #1 (06000003) 
------------------------------------------------------- 
    MethodName: op_Subtraction (06000003) 
    Flags  : [Public] [Static] [HideBySig] [ReuseSlot] [SpecialName] (00000896) 
    RVA  : 0x00002078 
    ImplFlags : [IL] [Managed] (00000000) 
    CallCnvntn: [DEFAULT] 
    ReturnType: I4 
    2 Arguments 
     Argument #1: Class ConsoleApplication21.MyClass1 
     Argument #2: Class ConsoleApplication21.MyClass1 
    2 Parameters 
     (1) ParamToken : (08000002) Name : i flags: [none] (00000000) 
     (2) ParamToken : (08000003) Name : j flags: [none] (00000000) 

Method #2 (06000004) 
------------------------------------------------------- 
    MethodName: op_Addition (06000004) 
    Flags  : [Public] [Static] [HideBySig] [ReuseSlot] [SpecialName] (00000896) 
    RVA  : 0x0000208c 
    ImplFlags : [IL] [Managed] (00000000) 
    CallCnvntn: [DEFAULT] 
    ReturnType: I4 
    2 Arguments 
     Argument #1: Class ConsoleApplication21.MyClass1 
     Argument #2: Class ConsoleApplication21.MyClass1 
    2 Parameters 
     (1) ParamToken : (08000004) Name : i flags: [none] (00000000) 
     (2) ParamToken : (08000005) Name : j flags: [none] (00000000) 

那麼,爲什麼C#編譯器生成的錯誤?

真的,奇怪的行爲:如果我參考MyClass1作爲DLL,它工作正常!

enter image description here 謝謝!

回答

3

Really, strange behavior: if i reference the MyClass1 as DLL, it works fine!

這說明了很多。 CLR將代碼編譯成一個程序集。在此之前,它會評估您使用的代碼,而不考慮特殊名稱簽名。該代碼給出編譯錯誤,因爲那時,還沒有匹配的超載。它仍然需要嵌入和編譯。 (這是一個chicken or the egg問題)

編譯後的程序集可以從另一個項目中使用,因爲程序集已經完全編譯了。

+0

Patrick Hofman,謝謝! 問題:在同一個文件中有一些方法告訴C#編譯器,誰需要先編譯?決定誰是雞蛋和誰是雞肉 – zzfima

+0

是的。通過使用C#語言中定義的方式,使用默認的重載方法。 –

相關問題