.net core下反射獲取string類型的Contains方法報錯:Ambiguous match found
感謝大佬,
這個是原文地址:http://www.rzrgm.cn/goldenbiu/articles/10755120.html
感謝大佬的解惑。 以下是大佬的原文:
========================================================================================================================================================
最近接手離職同事的代碼,調試過程中發現了一個反射類型報AmbiguousException的bug,總結如下:
以下代碼在.net framework 4.6.1中運行正常
|
1
|
var methodInfo = typeof(string).GetMethod("Contains"); |
放到.net core 2.1下就會報錯(.net core 2.0也是如此),

F12到string方法的內部,發現了如下問題:.net core下的string方法有多個Contains方法,反射方法就會提示多個match的Exception

OK,到這里問題算是定位到了,可是怎么解決呢?當然是求助于萬能的百度了,搜索后在微軟的官網上找到這篇文章:
https://www.baidu.com/link?url=3iqshQw5X72XkQL8opuqSOdYq_7-JNisK3-ebM2CIBeT1VsNz0jF4bQ1IcDuwBmrJWwn-hT0PwjmuMtgw-aTzJaI-Gl7nGueWo_B06L_oXjUdR2JZcC96lMWMMwEoGaMJ6W7YOVknqk47nkuaUbn6y-TwZSHm_E4nhyHkyRTShr3KrqQYPVLP7jdQChRqijskOHJk2DLgukRBk7s4VItK_&wd=&eqid=923ab58000009ad0000000045cbe7645
只需要在反射獲取方法的后面手動指定上類型,就能解決這個問題了:
|
1
|
var stringContainsMethod = typeof(string).GetMethod("Contains", new[] { typeof(string) }); |
項目中的代碼修改如下:
|
1
2
3
4
5
6
7
|
if (methodInfo.IsNull()){ if (instanceType == typeof(string)) methodInfo = typeof(string).GetMethod("Contains", new[] { typeof(string) }); else methodInfo = instanceType.GetMethod(methodName, BindingFlags.Instance | BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Static);} |
至此,問題成功解決! 看來升級為.net core中的坑點不少哇,還是需要悠著點。
========================================================================================================================================================
感謝大佬,
這個是原文地址:http://www.rzrgm.cn/goldenbiu/articles/10755120.html
浙公網安備 33010602011771號