首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >仅在生产环境中引发MulticastDelegate异常

仅在生产环境中引发MulticastDelegate异常
EN

Stack Overflow用户
提问于 2015-09-15 18:30:21
回答 3查看 398关注 0票数 5

我有一个非常奇怪的问题只发生在生产环境中。异常具有以下消息

“实例方法的代理不能具有空'this'”。

抛出异常的方法非常简单,并且工作了很长时间,所以问题必须是环境中一个模糊的依赖关系,或者类似的.

我使用的是ASP.NET Web,托管在Azure中,控制器的操作方法通过AJAX执行。

下面是抛出异常的代码:

代码语言:javascript
复制
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);
    }
}

下面是堆栈跟踪的相关部分:

代码语言:javascript
复制
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)

有人能找出这个异常的可能原因吗?提前谢谢。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2015-09-15 18:47:04

问题在于message实际上是null。您可以很容易地复制它:

代码语言:javascript
复制
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>构造函数,如下所示:

代码语言:javascript
复制
Func<string, bool> func = ((string)null).Contains;
return !split.Any(func);

这就是导致MulticastDelegate发疯的原因。您还可以在生成的IL中看到:

代码语言:javascript
复制
IL_0028:  ldftn       System.String.Contains
IL_002E:  newobj      System.Func<System.String,System.Boolean>..ctor
IL_0033:  call        System.Linq.Enumerable.Any

为了避免这种情况发生,也要确保您的空检查消息:

代码语言:javascript
复制
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);
}
票数 5
EN

Stack Overflow用户

发布于 2015-09-15 18:47:27

具有空this的委托是在结尾处使用的方法string.Contains(),它使用message变量作为this指针。换句话说,有一个调用message为null。

票数 3
EN

Stack Overflow用户

发布于 2015-09-15 18:41:49

当消息为空时失败。可以用这个

代码语言:javascript
复制
return !split.Any(part => (message != null && message.Contains(part)));
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32593157

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档