"指定的转换是无效"只有从MS构建发布版本版本、QUOT、MS

由网友(矮米思油)分享简介:从4.0的MSBuild只能做一个发布版本时我收到一个指定强制转换无效无效。我测试了这一点,在使用一个发布版本从Visual Studio 2012,并没有得到这个问题。我还测试了这一点,使用调试版本的MSBuild的4.0,并没有得到这个问题。 异常: code 公共抽象类CachedSessionBase:ISes...从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)在检索调用者的调用者。当该值从词典中检索,它是另一种类型的,因为它是一个不同的方法

sql server 2008 还原指定的转换无效

您可以尝试添加属性 [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.

阅读全文

相关推荐

最新文章