【问题标题】:error CS0027: Keyword 'this' is not available in the current context [duplicate]错误 CS0027:关键字“this”在当前上下文中不可用 [重复]
【发布时间】:2013-09-26 03:48:21
【问题描述】:

我有以下构造函数的初始化:

public partial class WizardPage1 : WizardPage
{
    public WizardPage1()
        : base(0, getLocalizedString(this.GetType(), "PageTitle"))
    {
    }
}

在哪里

public static string getLocalizedString(Type type, string strResID)
{
}

但this.GetType() 部分会导致以下错误:

错误 CS0027:关键字“this”在当前上下文中不可用

知道怎么解决吗?

【问题讨论】:

  • @miltonb:我不确定我错过了什么?其中一张海报只是将this 类型从基本构造函数中移出。我不能这样做,或者我宁愿使用其他方法来获取 this 类的类型?

标签: c# .net constructor


【解决方案1】:

“this”关键字指的是类的当前实例。在构造函数中,您无权访问该实例,因为您将要创建一个...所以请尝试以下操作:

public partial class WizardPage1 : WizardPage
{
    public WizardPage1()
        : base(0, getLocalizedString(typeof(WizardPage1), "PageTitle"))
    {
    }
}

【讨论】:

  • typeof(this) 有什么办法吗?恐怕我可能会错过更改“模板”类中的typeof(WizardPage1) 部分,这可能会导致麻烦......
  • @c00000fd - 一种可能的替代方法是在基类中使用泛型或反射,以便它可以自动收集您的意思 - 但没有防弹解决方案。如果您不能信任您的开发人员(包括您自己),请为错误和数小时痛苦的调试做好准备。
  • @c00000fd 你能用基本构造函数代码更新问题吗?
【解决方案2】:

this 关键字指的是类的当前实例,但是当您在构造函数中调用它时,您还没有要引用的实例(因为它正在被构造)。

也许另一种解决方案是在您的基类中拥有一个可以在子类中覆盖的属性。例如

public class WizardPage
{
   public virtual string PageTitle { get; }
   ...
}

public class WizardPage1 : WizardPage
{
   public override string PageTitle
   {
      get 
      {
          return getLocalizedString(this.GetType(), "PageTitle");
      } 
   }
}

这里的关键是当您已经拥有该对象的实例时,您正在调用GetType()。

【讨论】:

    【解决方案3】:

    @Damith 关于为什么这不起作用是正确的,但处理这个更简单的一种方法可能是(忽略实现细节):

    public abstract class WizardPage
    {
        // Replace or override existing constructor with this
        public WizardPage(int unknownInt, Type currentType, string str)
        {
            if (currentType == null)
                currentType = System.Reflection.MethodBase()
                                  .GetCurrentMethod().GetType();
    
            var localString = getLocalizedString(currentType, str);
    
            // Existing logic here
        }
    }
    

    并将您的子类更改为:

    public partial class WizardPage1 : WizardPage
    {
        public WizardPage1()
            : base(0, this.GetType(), "PageTitle")
        {
        }
    }
    

    不幸的是,如果您无权访问基类的代码,这种方法需要添加一个抽象层。

    【讨论】:

      猜你喜欢
      • 2020-12-28
      • 1970-01-01
      • 1970-01-01
      • 2013-10-16
      • 1970-01-01
      • 1970-01-01
      • 2012-09-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多