开发者

FieldAccessException when class accesses its own field (.NET project upgraded from 3.5 to 4.0)

开发者 https://www.devze.com 2023-01-10 08:36 出处:网络
I have a VB.NET solution, just upgraded from 3.5 to 4.0. One of the classes has a private field: Private _Projection As ICalculatedPath

I have a VB.NET solution, just upgraded from 3.5 to 4.0. One of the classes has a private field:

Private _Projection As ICalculatedPath

At runtime, any time the class containing that field accesses that field, I get a FieldAccessException. The first time that field happens to get accessed is a null check in a method, and one of the things I randomly tried is changing the above line to:

Private _Projection As ICalculatedPath = Nothing

When I do this, I get the FieldAccessException on that line saying that the class's .ctor() cannot access that field. I've also tried making the field protected and public, clean/rebuild solution, re开发者_Python百科starting VS, targeting x86 and .NET 4.0 specifically on every project in the solution, and other non-sensical measures to get rid of this Exception but to no avail. This code worked fine before the upgrade, of course.

Maybe something went wrong in the upgrade process? I'm not really sure what to think here.


It looks like this has to do with the deprecation of Code Access Security in .NET 4.0. The assembly containing this class had the following in its AssemblyInfo.vb:

<Assembly: AllowPartiallyTrustedCallers()> 

Removing that attribute causes the FieldAccessException to not occur. Exactly why this is the case, I don't know, but it does get rid of the exception. If someone can fill in more details I'm sure they will be useful to anyone who finds this question in the future.

In our case this attribute was necessary because we were using the MS ReportViewer control with nested object data sources. We no longer need it, so it is a happy coincidence that getting rid of it is not a problem.


Have you also explitly declared a property in the same class called Projection? VB.NET automatically creates a private field with a leading underscore for any automatic properties you declare. So if you had Public Property Project As ICalculatedPath without declared getters and setters (this is called an automatic property, which I believe was introduced in VB.NET 4.0), VB.NET will automatically generate _Projection. In that case, the program would have two variables with the same declaration in the same scope, which would be a problem.

0

精彩评论

暂无评论...
验证码 换一张
取 消