c# code seems to get optimized in an invalid way such that an object value becomes null

后端 未结 3 774
萌比男神i
萌比男神i 2021-02-05 13:13

I have the following code that exhibits a strange problem:

var all = new FeatureService().FindAll();
System.Diagnostics.Debug.Assert(all != null, \"FindAll must          


        
3条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-05 14:05

    After Lasse discovered that the FindAll method was generating the wrong IL, I then came across another method that was also generating the wrong IL -- I also found the root cause and resolution.

    The relevant line in the second method is:

    var policy = Cache.GetDefaultCacheItemPolicy(dependentKeys, true);
    

    Cache is my own object. The GetDefaultCacheItemPolicy method returns a System.Runtime.Caching.CacheItemPolicy object. The generated IL, however, looked like this:

    Func policy = (Func) base.Cache.GetDefaultCacheItemPolicy(dependentKeys, true);
    

    There are two projects in play here. The methods that are generating the wrong IL are in one project called DomainModel, and the Cache object is in a Utilities project, which is referenced by the first. The second project contains a reference to System.Runtime.Caching but the first does not.

    The fix was to add a reference to System.Runtime.Caching to the first project. Now the generated IL looks correct:

    CacheItemPolicy policy = base.Cache.GetDefaultCacheItemPolicy(dependentKeys, true);
    

    The first method (that Lasse posted about in his answer) now also generates proper IL.

    Hooray!

提交回复
热议问题