下面是我的Windows服务代码。当我调试代码时,我得到错误/异常:

CSMessageUtility的类型初始化式。CSDetails抛出了一个异常。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.IO;
using System.Threading;
using System.Windows;
using System.Windows.Forms;
using CSMessageUtility;

namespace CS_Data_Trasmmiting_Service
{
    public partial class svcCSWinServ : ServiceBase
    {
        //private string sLogFormat;
        //private string sErrorTime;
        private Thread new_thread;
        Logger logObject = new Logger();
        private bool isenable = true;

        public svcCSWinServ()
        {
            InitializeComponent();
            logObject.append("Initialize Service " + DateTime.Now.ToString(), 70);
            CheckForAlarms();
        }

        protected override void OnStart(string[] args)
        {
            try
            {
                new_thread = new Thread(new ThreadStart(CheckForAlarms));
                new_thread.Start();
            }
            catch
            {
            }

            logObject.append("Service Started successfully " + DateTime.Now.ToString(), 70);
        }

        protected override void OnStop()
        {
            try
            {
                isenable = false;
                new_thread.Abort();
            }
            catch
            {

            }
            logObject.append("Service Stopped successfully " + DateTime.Now.ToString(), 70);
        }


        void CheckForAlarms()
        {
            try
            {
                while (true)
                {
                    //if((DateTime.Now.ToString("HH:mm") == "18:00"))
                    //{

                        logObject.append("Start Sending Data " +DateTime.Now.ToString(), 70);
                        try
                        {
                            //SendAllInfo();
                            string str = CSMessageUtility.CSDetails.createDHSMessageFormat();
                            Thread.Sleep(2000);
                            string str1 = CSMessageUtility.CSDetails.createEALMessageFormat();
                            Thread.Sleep(2000);
                            string str2 = CSMessageUtility.CSDetails.createProductStatusMessageForamt();
                            Thread.Sleep(2000);
                            string str3 = CSMessageUtility.CSDetails.createEODMessageFormat();
                            Thread.Sleep(2000);
                            string str4 = CSDetails.createProductReceiptEntryatBOSMessageFormat();
                            Thread.Sleep(2000);
                            string str5 = CSMessageUtility.CSDetails.createProductSaleMessageFormat();
                            Thread.Sleep(2000);
                            string str6 = CSMessageUtility.CSDetails.createTotalizerExceptionMessageFormat();
                            Thread.Sleep(2000);
                            //CSMessageUtility.CSDetails.createDailyCOtransferMessageFormat();
                            //Thread.Sleep(2000);

                        }
                        catch (Exception ee)
                        {
                            logObject.append(ee.Message, 70);
                        }
                        logObject.append("Finished Sending Data " +DateTime.Now.ToString(), 70);
                        Thread.Sleep(3000);
                    //}
                    //Thread.Sleep(20000);
                }
            }
            catch (Exception ex)
            {
                logObject.append("Thread Exception: "+ ex.Message + " "+ DateTime.Now.ToString(), 70);

                try
                {
                    new_thread.Abort();
                }
                catch (Exception ex1)
                {
                    logObject.append("Thread Exception: " +ex1.Message + " " + DateTime.Now.ToString(), 70);
                }

                if (isenable == true)
                {
                    new_thread = new Thread(new ThreadStart(CheckForAlarms));
                    new_thread.Start();
                }
            }
        }
    }
}

当前回答

如果您的依赖项属性注册到错误的所有者类型(ownerType参数),就会发生这种情况。

注意SomeOtherControl应该是YourControl。

public partial class YourControl
{
    public bool Enabled
    {
        get { return (bool)GetValue(EnabledProperty);   }
        set { SetValue(EnabledProperty, value); }
    }
    public static readonly DependencyProperty EnabledProperty =
        DependencyProperty.Register(nameof(Enabled), typeof(bool), typeof(SomeOtherControl), new PropertyMetadata(false));
}

其他回答

类似穆罕默德·伊克巴尔所说的…我在一个VB。NET(也可能是c#)项目,其中我从App.config中删除了一个键值对,它由一个全局变量引用到模块Main的Sub Main()。因此,异常(和break)在子Main()之前发生在Module Main中。如果我在Dim上有断点就好了,但我们通常不会在全局变量上中断。也许一个很好的理由不声明全局引用App.config?换句话说,这个…

类型为“System”的未处理异常。在未知模块中发生TypeInitializationException'。 命名空间的类型初始化式。Main'抛出了一个异常。

是由……

App.config

<connectionStrings>
    <!--<add name="ConnectionString1" connectionString="..." />-->

主模块

Module Main
    Dim cnnString As String = ConfigurationManager.ConnectionStrings("ConnectionString1")  '<-- BREAK HERE (EXCEPTION)

    Sub Main()

        // main code

    End Main
End Module

在WPF项目中有一个类似的案例。我的问题是这样写的:

DataTable myTable = FillTable(strMySqlQuery);

FillTable()返回一个基于SQL查询字符串的数据表。如果我做了“复制例外到剪贴板”选项,我认为它是,并粘贴到记事本,我可以看到消息。对我来说,它是输入不是一个有效的Base-64字符串,因为它包含一个非Base-64字符。

My actual problem wasn't that the query string had something that shouldn't be there, like I was thinking, because string strMySqlQuery = "SELECT * FROM My_Table" was my string and thought it could be the * or _, but the actual problem was in FillTable(), where I had a call to another function, GetConnection() that returned an OracleConnection object, in order to open it and retrieve and return the DataTable. Inside GetConnection() I was getting the app.config parameters for my connection string, and I had one of them misnamed, so it was setting a null value for the service account's password and not making the DB connection. So it's not always where the error is exactly correct for all circumstances. Best to dive into the function where the error is and debug step-by-step and ensure all values are getting filled with what you expect.

值得注意的是:在我的解决方案中有多个项目,我忘记添加引用/Nuget库。当我在静态类中运行一个使用给定库的方法时,它抛出了上面提到的异常。

CSMessageUtility的类型初始化式。CSDetails抛出了一个异常。意味着该类的静态构造函数抛出了一个异常——所以你需要在CSDetails类的静态构造函数中查找,或者在该类的任何静态成员的初始化中查找。

我在try-catch块中包装了即将崩溃的行,打印出异常,并在打印后立即中断。所显示的异常信息具有堆栈跟踪,它将我指向导致故障发生的文件和代码行。

System.TypeInitializationException: The type initializer for 'Blah.blah.blah' threw an exception. 
---> System.NullReferenceException: Object reference not set to an instance of an object.
   at Some.Faulty.Software..cctor() in C:\Projects\My.Faulty.File.cs:line 56
   --- End of inner exception stack trace ---
   at Blah.blah.blah(Blah.blah.blah)
   at TestApplication.Program.Main(String[] args) 
   in C:\Projects\Blah.blah.blah\Program.cs:line 29 Exception caught.