类型初始化器

Pos*_*Guy 4 c#

我有一个配置类:

namespace SomeCompanyName.SomeAppName
{
    public static class MyConfigClass
    {
        public static readonly string ConsKey = Config.GetAppConfigSetting("ConsKey");
        public static readonly string ConsSecret = Config.GetAppConfigSetting("ConsSecret");
     }
}
Run Code Online (Sandbox Code Playgroud)

我有一种方法试图在字典中使用其中一些值:

public HttpWebResponse SomeMethod(....)
{

    Dictionary<string, string> headerParams = new Dictionary<string, string> {
        {Constants.Cons, MyConfigClass.ConsumerKey},
        {Constants.Token, MyConfigClass.SingleAccessToken},
        {Constants.ignatureMethod, Constants.SignatureMethodTypeHMACSHA1},
        {Constants.Timestamp, HttpUtility.GenerateTimeStamp()
    };
}
Run Code Online (Sandbox Code Playgroud)

由于某种原因,我收到此错误:

“'SomeAppConfig' 的类型初始值设定项引发了异常。”

不知道为什么 SomeAppConfig 类是静态的。

更新:

这是 GetAppConfigSetting 的定义:

public class Config
{
    public static string GetAppConfigSetting(string configKey)
    {
        return ConfigurationManager.AppSettings[configKey] ?? string.Empty;
    }
}
Run Code Online (Sandbox Code Playgroud)

更新:

这是我的测试项目中的 app.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>

  <appSettings>
    <add key="ConsKey" value="HHGRT6jV4M" />
    <add key="ConsSecret" value="QR47dbduycAc" />
  </appSettings>

</configuration>
Run Code Online (Sandbox Code Playgroud)

das*_*ght 5

静态类的类型初始值设定项是设置其静态变量值的代码。在你的情况下,它是这个代码:

public static readonly string ConsKey = Config.GetAppConfigSetting("ConsKey");
public static readonly string ConsSecret = Config.GetAppConfigSetting("ConsSecret");
Run Code Online (Sandbox Code Playgroud)

确保GetAppConfigSetting可以访问ConsKey并且ConsSecret没有问题。从初始化程序抛出的异常应该有更多信息来帮助您调试问题。