.net core下反射获取string类型的Contains方法报错:Ambiguous match found

感谢大佬,
这个是原文地址:https://www.cnblogs.com/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中的坑点不少哇,还是需要悠着点。

 

========================================================================================================================================================

感谢大佬,
这个是原文地址:https://www.cnblogs.com/goldenbiu/articles/10755120.html

 

posted @ 2022-11-18 09:14  .NetCat  阅读(93)  评论(0编辑  收藏  举报