我有一个非常奇怪的问题只发生在生产环境中。异常具有以下消息
“实例方法的代理不能具有空'this'”。
抛出异常的方法非常简单,并且工作了很长时间,所以问题必须是环境中一个模糊的依赖关系,或者类似的.
我使用的是ASP.NET Web,托管在Azure中,控制器的操作方法通过AJAX执行。
下面是抛出异常的代码:
public class BlacklistService : IBlacklistService
{
public bool Verify(string blacklist, string message)
{
if (string.IsNullOrEmpty(blacklist)) return true;
var split = blacklist.ToLower().Split(';'); // exception is thrown here
return !split.Any(message.Contains);
}
}下面是堆栈跟踪的相关部分:
at System.MulticastDelegate.ThrowNullThisInDelegateToInstance()
at System.MulticastDelegate.CtorClosed(Object target, IntPtr methodPtr)
at MyApp.Business.Services.BlacklistService.Verify(String blacklist, String message)
at MyApp.Business.Services.ContactMessageFactory.GetVerifiedStatus(String mensagem)
at MyApp.Business.Services.ContactMessageFactory.GetMailMessage(ContactForm contactForm)
at MyApp.Business.ContactEmailService.Send(ContactForm contactForm)有人能找出这个异常的可能原因吗?提前谢谢。
发布于 2015-09-15 18:47:04
问题在于message实际上是null。您可以很容易地复制它:
void Main()
{
Verify("hello", null);
}
public bool Verify(string blacklist, string message)
{
if (string.IsNullOrEmpty(blacklist)) return true;
var split = blacklist.ToLower().Split(';'); // exception is thrown here
return !split.Any(message.Contains);
}通过方法组转换将message.Contains传递给Func<string, bool>构造函数,如下所示:
Func<string, bool> func = ((string)null).Contains;
return !split.Any(func);这就是导致MulticastDelegate发疯的原因。您还可以在生成的IL中看到:
IL_0028: ldftn System.String.Contains
IL_002E: newobj System.Func<System.String,System.Boolean>..ctor
IL_0033: call System.Linq.Enumerable.Any为了避免这种情况发生,也要确保您的空检查消息:
public bool Verify(string blacklist, string message)
{
if (string.IsNullOrEmpty(blacklist)) return true;
if (string.IsNullOrEmpty(message)) return false;
var split = blacklist.ToLower().Split(';'); // exception is thrown here
return !split.Any(message.Contains);
}发布于 2015-09-15 18:47:27
具有空this的委托是在结尾处使用的方法string.Contains(),它使用message变量作为this指针。换句话说,有一个调用message为null。
发布于 2015-09-15 18:41:49
当消息为空时失败。可以用这个
return !split.Any(part => (message != null && message.Contains(part)));https://stackoverflow.com/questions/32593157
复制相似问题