C# 错误“...的类型初始值设定项引发异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1226188/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 13:54:36  来源:igfitidea点击:

C# Error "The type initializer for ... threw an exception

c#classstatic

提问by Vytas

This error occurs only in some computers. By reading the stack information, there is some problem when I call to this static method ("FormatQuery") in a static class:

此错误仅在某些计算机中发生。通过读取堆栈信息,当我在静态类中调用这个静态方法(“FormatQuery”)时会出现一些问题:

using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using FlexCel.Report;
using FlexCel.XlsAdapter;
using ComboBox=System.Windows.Forms.ComboBox;

namespace XSoftArt.A
{
    static class RHelper
    {
        private static string FormatQuery(string FieldName, int Count,
            CheckedListBox chekedListBox)
        {
            string ID = string.Empty;
            int n = Count;

            foreach (DataRowView item in chekedListBox.CheckedItems)
            {
                ID = ID + item["" + FieldName + ""];
                if (n > 1)
                {
                    ID = ID + " , ";
                    n--;
                }
            }
            return ID;
        }

        public static string FormatQuery(CheckedListBox chekedListBox)
        {
            return FormatQuery(chekedListBox.ValueMember,
                chekedListBox.CheckedItems.Count, chekedListBox);
        }
    }

So, what's the problem? How do I solve it? Is there something wrong with the project configuration or debbuging mode or what?

所以有什么问题?我该如何解决?项目配置或调试模式有问题还是什么?

Error information:

错误信息:

   at XSoftArt.EVS.ReportHelper.FormatQuery(CheckedListBox chekedListBox)
   at XSoftArt.EVS.NewEmailSelectClient.LoadList_v2(String search, TextBox txtbox)
   at XSoftArt.EVS.NewEmailSelectClient.LoadContacts()
   at XSoftArt.EVS.NewEmailSelectClient.button7_Click(Object sender, EventArgs e)
   at System.Windows.Forms.Control.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
   at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.ButtonBase.WndProc(Message& m)
   at System.Windows.Forms.Button.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

采纳答案by TheVillageIdiot

I tried your code:

我试过你的代码:

CheckedListBox cb = new CheckedListBox();
for (var i = 1; i < 11; i++)
  cb.Items.Add("Item " + i, i % 3 == 0);

string fmt = RHelper.FormatQuery(cb);
Console.WriteLine(fmt);
Console.ReadLine();

It threw an exception at this line:

它在这一行抛出了一个异常:

foreach (DataRowView item in chekedListBox.CheckedItems)

// Unable to cast object of type 'System.String' to type 'System.Data.DataRowView'.

Maybe you are also facing the same kind of problem. Instead of casting to DataRowView, try making the following changes:

或许你也面临着同样的问题。不要强制转换为DataRowView,而是尝试进行以下更改:

foreach (var item in chekedListBox.CheckedItems)
{
    ID = ID + item.ToString(); // item["" + FieldName + ""];

Because items in CheckedListBox are of objecttype.

因为 CheckedListBox 中的项目是对象类型的。

回答by Anderson Imes

A Type Initializer exception indicates that the type couldn't be created. This would occur typically right before your call to your method when you simply reference that class.

类型初始值设定项异常表示无法创建该类型。当您简单地引用该类时,这通常会在您调用您的方法之前发生。

Is the code you have here the complete text of your type? I would be looking for something like an assignment to fail. I see this a lot with getting app settings and things of that nature.

你这里的代码是你类型的完整文本吗?我会寻找类似任务失败的东西。我在获取应用程序设置和这种性质的东西时看到了很多。

static class RHelper
{
     //If this line of code failed, you'd get this error
     static string mySetting = Settings.MySetting;
} 

You can also see this with static constructors for types.

您还可以通过类型的静态构造函数看到这一点。

In any case, is there any more to this class?

无论如何,这门课还有什么吗?

回答by Jay Stratemeyer

If you have web services, check your URLpointing to the service. I had a simular issue which was fixed when I changed my web service URL.

如果您有 Web 服务,请检查指向该服务的URL。我有一个类似的问题,当我更改 Web 服务 URL 时已解决。

回答by jeb

I got this error with my own code. My problem was that I had duplicate keys in the config file.

我用自己的代码遇到了这个错误。我的问题是我在配置文件中有重复的键。

回答by Eternal21

I got this error when trying to log to an NLog target that no longer existed.

尝试登录到不再存在的 NLog 目标时出现此错误。

回答by TheMethod

I had this problem and like Anderson Imes said it had to do with app settings. My problem was the scope of one of my settings was set to "User" when it should have been "Application".

我遇到了这个问题,就像 Anderson Imes 所说的,这与应用程序设置有关。我的问题是我的一项设置的范围设置为“用户”,而本应为“应用程序”。

回答by James McKeon

I got this error when I modified an Nlog configuration file and didn't format the XML correctly.

当我修改 Nlog 配置文件并且没有正确格式化 XML 时出现此错误。

回答by Kevin Morwood

I had the same error but in my case it was caused by mismatch in platform target settings. One library was set specifically to x86 while the main application was set to 'Any'...and then I moved my development to an x64 laptop.

我有同样的错误,但在我的情况下,它是由平台目标设置不匹配引起的。一个库专门设置为 x86,而主应用程序设置为“任何”……然后我将我的开发转移到了 x64 笔记本电脑。

回答by Muhammad Waqas Iqbal

This problem can occur if a class tries to get value of a non-existent key in web.config.

如果一个类尝试获取web.config.

For example, the class has a static variable ClientID

例如,该类有一个静态变量 ClientID

private static string ClientID = System.Configuration.ConfigurationSettings.AppSettings["GoogleCalendarApplicationClientID"].ToString();

but the web.configdoesn't contain the 'GoogleCalendarApplicationClientID' key, then the error will be thrown on any static function call or any class instance creation

web.config不包含“GoogleCalendarApplicationClientID”键,则任何静态函数调用或任何类实例创建都会引发错误

回答by user3302664

This error was generated for me by having an incorrectly formatted NLog.config file.

此错误是由格式不正确的 NLog.config 文件为我生成的。