"指定的转换是无效"只有从MS构建发布版本 [英] "Specified cast is not valid" only on release build from MS build

查看:182
本文介绍了"指定的转换是无效"只有从MS构建发布版本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从4.0的MSBuild只能做一个发布版本时

我收到一个指定强制转换无效无效。我测试了这一点,在使用一个发布版本从Visual Studio 2012,并没有得到这个问题。我还测试了这一点,使用调试版本的MSBuild的4.0,并没有得到这个问题。

异常:

code

 公共抽象类CachedSessionBase:ISessionObject
{
    保护字典< MethodBase,对象> _getAndSetCache =新字典< MethodBase,对象>();

    保护TResult SetAndGet< TResult>(ObjectFactory的工厂,Func键< TResult> FUNC)
    {
        堆栈跟踪堆栈跟踪=新的堆栈跟踪();
        变种methodBase = stackTrace.GetFrame(1).GetMethod();

        如果(!_getAndSetCache.ContainsKey(methodBase))
        {
            _getAndSetCache [methodBase] = func.Invoke();
        }

        返程(TResult)_getAndSetCache [methodBase]
    }
 

该错误被扔在这条线

 收益率(TResult)_getAndSetCache [methodBase]
 

解决方案

这是可能的调用堆栈是比你期望它是不同的。你的方法可以得到内联,那么的getFrame(1)在检索调用者的调用者。当该值从词典中检索,它是另一种类型的,因为它是一个不同的方法

您可以尝试添加属性 [MethodImpl(MethodImplOptions.NoInlining] SetAndGet 来prevent的内联优化的方法。

I am getting a "Specified cast is not valid" valid when doing only a release build from MSBuild 4.0. I tested this out in using a release build from Visual Studio 2012 and didn't get this issue. I also tested this out using a debug build from MSBuild 4.0 and didn't get this issue.

Exception:

Code

    public abstract class CachedSessionBase : ISessionObject
{
    protected Dictionary<MethodBase, Object> _getAndSetCache = new Dictionary<MethodBase, object>();

    protected TResult SetAndGet<TResult>(ObjectFactory factory, Func<TResult> func)
    {
        StackTrace stackTrace = new StackTrace();
        var methodBase = stackTrace.GetFrame(1).GetMethod();

        if (!_getAndSetCache.ContainsKey(methodBase))
        {
            _getAndSetCache[methodBase] = func.Invoke();
        }

        return (TResult)_getAndSetCache[methodBase];
    }

The error is being thrown on this line

return (TResult)_getAndSetCache[methodBase];

解决方案

It is likely that the call stack is different than what you are expecting it to be. Your method may be getting inlined, then GetFrame(1) is retrieving the caller's caller. When the value is retrieved from the dictionary, it is of a different type because it is for a different method.

You could try adding the attribute [MethodImpl(MethodImplOptions.NoInlining] to SetAndGet to prevent the inlining optimization for the method.

这篇关于&QUOT;指定的转换是无效&QUOT;只有从MS构建发布版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆