c# - 为什么会发生 System.TypeInitializationException?
问题描述
我正在尝试在 c# 中使用 WebClient 类,并且我需要它作为方法和事件侦听器,所以我在一个类中定义了它。当我尝试运行我的程序时,发生 System.TypeInitializationException,我不知道为什么。我一直在寻找解决方案,但找不到。
这是我的代码(已编辑):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading;
using System.Speech.Synthesis;
using System.Windows.Forms;
using System.Net;
class Program
{
static WebBrowser browser1 = new WebBrowser();
static void Main(string[] args)
{
//some code
browser1.DocumentCompleted += webBrowser1_DocumentCompleted;
}
static void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
//some code
Main(null);
}
}
当我注释掉 WebBrowser 变量和任何需要它的代码时,代码工作正常。请帮助我,因为我是 C Sharp 的新手。
解决方案
错误说
ThreadStateException: ActiveX control '8856f961-340a-11d0-a96b-00c04fd705a2' cannot be
instantiated because the current thread is not in a single-threaded apartment.
在 main 方法上方添加 STAThread 属性
[STAThread]
static void Main(string[] args)
推荐阅读
- java - 如果调用 scheduleWithFixedDelay 方法的次数超过池大小,ScheduledExecutorService 如何工作?
- javascript - 如何更改 JavaScript 中的舍入规则?
- python - 根据空格拆分段落并删除多余的空格
- android - 自定义视图焦点区域
- java - 使用 SpringExtension.beforeAll 时 @BeforeAll 的 AbstractMethodError
- php - CodeIgniter - 我如何进行分页?
- halcon - Halcon FindNccModel 导致 C# 中的内存泄漏
- wpf - 当我运行 wpf 项目应用程序时,组合框没有响应鼠标单击并且没有出现下拉列表
- go - 如何发送动态 json 键/值作为请求参数
- c# - 如何使物体停在特定位置