【问题标题】:C# Keyword 'this' is not available in the current contextC# 关键字“this”在当前上下文中不可用
【发布时间】:2020-12-28 04:33:11
【问题描述】:

我有一个接口 Service,它有一个 GoTo 方法

 public interface Service
 {
   bool GoTo(string NextPage , object parameter);
 }

我有一个A类如下

 public class A
 {
    private Service serviceA;

   //constructor of the class
   public A(Service serviceB, ServiceManager serviceManager)
   {
      this.serviceA = serviceB;
   }
   public ObservableCollection<SampleObject> Example { get; } = new 
   ObservableCollection<SampleObject>()
    {
        new SampleObject() { Action=  new DelegateCommand(() => this.serviceA.GoTo("NextPage", null)) 
    },
     
    };

}

我收到一个错误,说关键字“this”在当前上下文中不可用。我查看了A field initializer cannot reference the nonstatic field, method, or property,我可以看到该错误是由于变量未在构造函数中初始化但在我的情况下我这样做了。任何有助于更好地理解这一点的帮助将不胜感激?

【问题讨论】:

  • “但在我的情况下,我这样做了” - 不,你没有,你在声明时初始化属性。如果您只是将代码更改为将Example = new ObservableCollection&lt;SampleObject&gt;() { ... } 放入构造函数 就可以了。

标签: c#


【解决方案1】:

此代码中的thisnew SampleObject() { Action= new DelegateCommand(() =&gt; this.serviceA.GoTo("NextPage", null))在SampleObject的范围内,而不是A的范围内。

不是您问题的确切答案,但将 camelCase 用于私有字段是一种非常糟糕的做法,即使它符合 C# 标准约定。 .Net 社区中广泛使用的约定是使用前导下划线命名私有字段。例如:private Service _serviceA;

这种约定有助于避免这种情况下的变量命名冲突,并减少使用全局变量和局部变量时的人为错误。

【讨论】:

    【解决方案2】:

    你可以通过声明一个变量(例如that)来保存this的值来解决这个问题。例如:

    var that = this;
    

    然后在现有代码中将this 替换为that:

    that.serviceA.GoTo("NextPage", null)
    

    您需要将 Example 的属性 lambda 替换为适当的 get 块。该块的第一条语句应该是上面的var 代码。

    (这是 JavaScript 中的一种常用技术,不是因为this 永远“不可用”,而是因为this 的上下文不是你想要它在你想使用它的地方。但是它偶尔也会在 C# 中派上用场。)

    【讨论】:

    • 您能否展示如何将这种技术与 OP 的代码一起使用?
    • 我上面的代码不是贴出来的吗?需要放完整的代码吗?
    【解决方案3】:

    您在属性初始化程序中使用this。你不能那样做。您所要做的就是将 Example 的初始化从声明点移到构造函数主体中:

    public class A
    {
        private Service serviceA;
        public ObservableCollection<SampleObject> Example { get; }
    
        public A(Service serviceB, ServiceManager serviceManager)
        {
            this.serviceA = serviceB;
            Example = new ObservableCollection<SampleObject>
            {
                new SampleObject
                {
                    Action = new DelegateCommand(() => this.serviceA.GoTo("NextPage", null))
                }
            };
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-22
      • 1970-01-01
      • 1970-01-01
      • 2015-02-28
      • 1970-01-01
      相关资源
      最近更新 更多