Does anyone know why the constructor of an attribute decorating the main method is called in debug builds, 开发者_如何学Gobut not in release builds?
How can I ensure that the constructor is called in release builds as well? Without calling it manually of course.Any insight on this subject would be very much appreciated.
I can reproduce this (in both debug and release), when executed via the IDE with the "Debug" => "Enable the Visual Studio hosting process" option enabled, via the below. At the command-line it will print "hello", where-as via the IDE it will print "world". It looks like the IDE is doing some different reflection on the attributes.
This is not expected behaviour, and you should not rely on this behaviour. If you want some particular code to execute: invoke the desired code explicitly. To get predictable behaviour, disable the Debug" => "Enable the Visual Studio hosting process" option.
using System;
public class MyTestAttribute : Attribute {
public MyTestAttribute() {
Program.text = "world";
}
}
class Program {
public static string text = "hello";
[MyTest]
static void Main() {
Console.WriteLine(text);
Console.ReadKey();
}
}
精彩评论