Skip to main content
 首页 » 编程设计

c#之如何最好地调试 "The type initializer for xx class threw an exception"

2024年02月23日37mengfanrong

我有一个用户报告了这个异常。我在这里和其他地方的研究表明这是一个静态构造函数错误。有关的类包含许多已初始化的静态字段。我认为它是其中之一,但我不确定如何找到它。该建议似乎是在静态构造函数中包含一个 try/catch block 。如所写,没有明确的静态构造函数。

我在想我应该写一个显式静态构造函数,将静态字段的初始化移到其中并将它们包装在 try/catch block 中。我知道我可以尝试这个,但我不会出现错误,我想向用户发送一个修改后的可执行文件来尝试。我的应用程序确实记录了错误,所以如果在静态构造函数中捕获到异常,我应该从他那里得到一个日志。

类的相关(我希望)部分在这里(它实际上不是我的代码,但我可以根据需要修改它):

 [Serializable] 
    public class PText : PNode, ISerializable { 
 
    //comments elided by edit for brevity 
        #region Fields 
 
        public const int PROPERTY_CODE_FONT = 1 << 18; 
        public const int PROPERTY_CODE_TEXT = 1 << 17; 
        public static Font DEFAULT_FONT = new Font("Arial", 12); 
        protected static readonly object PROPERTY_KEY_FONT = new object(); 
        protected static readonly object PROPERTY_KEY_TEXT = new object();  
        private static Graphics GRAPHICS = Graphics.FromImage(new Bitmap(1, 1)); 
 
        [NonSerialized] 
        private Color brushColor; 
        private bool constrainHeightToTextHeight = true; 
        private bool constrainWidthToTextWidth = true; 
        private Font font; 
 
        [NonSerialized] 
        private Color penColor; 
 
        [NonSerialized] 
        private StringFormat stringFormat = new StringFormat(); 
        private String text; 
 
        [NonSerialized] 
        private Brush textBrush; 
 
        #endregion Fields 
 
        #region Constructors 
        public PText() { 
            textBrush = Brushes.Black; 
        } 
 
        public PText(String aText) 
            : this() { 
            Text = aText; 
        } 
 
        protected PText(SerializationInfo info, StreamingContext context) 
            : base(info, context) { 
            textBrush = PUtil.ReadBrush(info, "textbrush"); 
            TextAlignment = (StringAlignment)info.GetValue("alignment", typeof(int)); 
        } 
 
        #endregion Constructors 
....... 

请您参考如下方法:

回答你的问题,你的想法很好。在可能抛出的行周围放置一个 try/catch,然后在它变成 TypeInitializationException 之前记录错误。

或者,更改为使用 Lazy - 这会将异常更改为首次访问的位置。这可能对您有用,也可能没有用,但它帮助我调试了类似的问题。