문제

I have a small C# class with a few unsafe methods. Is there a way to specify "/unsafe" option declaratively in C# source code (with #pragma or anyhow else) just for the context of the class' source file? I'd hate to create a separate assembly for such a small class, but I also really don't want the rest of the assembly (the class is currently a part of) to be enabled for unsafe code.

도움이 되었습니까?

해결책

No, this is (currently) not possible, as the entire assembly is affected by having unsafe code in it.

By including unsafe code in your assembly, you are telling the CLR that the assembly could do something, well, unsafe, which changes how the runtime acts when it loads the assembly. The biggest change here is that the CLR will simply not try to verify your unsafe code, but it also will refuse to load your assembly unless it has full-trust (e.g. you couldn't load an unsafe assembly as a normal user over click-once.)

From a technical perspective, when you use the /unsafe option, it causes the compiler to emit the IL equivalent of the following module-level attributes into your assembly:

[assembly:SecurityPermission(SkipVerification = true)]
[assembly:UnverifiableCode]

Your best option is, as you said, to isolate the unsafe code into its own separate assembly as much as possible. The fact that the assembly has only one class in it is much less of a code-smell than tainting an entire assembly full of safe code due to one unsafe class.

다른 팁

C# has an unsafe keyword that you have to use around unsafe code, just to avoid having people using unsafe code by accident. This is as good an approach as any I can think of: If someone can introduce the unsafe keyword in a file, they could just as easily add or remove a #pragma tag or some such.

The /unsafe compiler tag tells the compiler that you're okay with people using the unsafe keyword in this assembly, and you recognize that the assembly it generates will be marked "unsafe," which may prevent it from running in less-than-Full-Trust environments. There's no way to have the compiler mark only individual classes as unsafe: people can either trust your assembly or they can't.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top