【问题标题】:Field initializer cannot reference non static field, method, property [duplicate]字段初始化程序不能引用非静态字段、方法、属性
【发布时间】:2018-01-30 05:16:27
【问题描述】:

我正在使用MailChimpbrandonseydel 的库,我无法创建“MailChimpManager”对象,收到错误字段初始化程序无法引用非静态字段、方法、属性

 public string MailChimpAPIKey {
        get
        {
            using (BEntities entity=new BEntities())
            {
                var key = entity.tbl_Client_MailChimp_Settings.Where(p => p.CIN == CINNo).FirstOrDefault();
                if (key != null)
                    return key.APIKey;
                else
                    return "";
            }
        }
    }

    private static MailChimpManager Manager = new MailChimpManager(MailChimpAPIKey);

【问题讨论】:

  • 错误不言自明。您正在尝试在静态方法中访问非静态对象。删除静态或将 MailChimpAPIKey 设为静态。

标签: c# mailchimp


【解决方案1】:

您正在尝试将非静态文件与静态类一起使用。将您的MailChimpAPIKey 设为静态,它将起作用。也尝试为MailChimpAPIKey 实现setter。

【讨论】:

  • 我试过了,但我正在根据 MailChimpAPIKey 属性中的 CIN 获取记录,CINNo 又是一个非静态属性
  • 从 MailChimpManager 中移除静态。您保留的内容是私密的,因此无法在任何地方访问。
  • 如何获取登录的用户ID并将其存储在asp.net mvc的静态变量中
  • 这是不同的错误或你问的问题。您可以为此开始单独的问题。如果这对您有帮助,请点赞并标记为答案。
【解决方案2】:

MailChimpAPIKey 也必须是静态的,或者 IMailChimpManager 的实现必须是非静态的

private IMailChimpManager Manager = new MailChimpManager(MailChimpAPIKey);

【讨论】:

    猜你喜欢
    • 2018-11-30
    • 1970-01-01
    • 1970-01-01
    • 2011-11-16
    • 2013-01-04
    • 2022-01-23
    相关资源
    最近更新 更多