"static method requires null instance non-static method requires non-null instance" Anonymous Method difference between 2012 and 2017

  • 303
  • 0

static method requires null instance non-static method requires non-null instance 這是最近碰上滿有趣的錯誤

static method requires null instance non-static method requires non-null instance

這是最近碰上滿有趣的錯誤,  看完這樣的描述, 只覺得是很合理一句話.

往程式碼研究, 錯誤是發生 Expression.Call . 確定參數後, 它能執行的是靜態方法.

OK, 接下來就是要找上面傳來了什麼 Method 的 Methodinfo.

接著就看到了一個 lambda expression.

大概是這麼寫的.

private static Methodinfo = new Func<DateTime, string>(n => n.ToString("MM/dd/yyyy")).Method;

這樣的程式在之前都成功, 在最近安裝2017後碰上問題要debug才在本機出現.

很直覺的聯想到compiler 

分別用不同的版本開啟後, 建置完 用ildasm開啟dll

發現果然有所不同.

以下是2012

以下是2017

一個是 static, 一個是 instance. 

2012 編譯自動產生出來的是靜態方法, 所以之前都一直沒問題.

最後是將該 lambda expression 獨立成一個靜態方法

程式就不會有問題了.

如果 lambda expression 裡面有使用到外部的變數

編譯完的結果, 2012 與 2017都是一致的 instance method.

記錄一下這個有趣的東西.