7

コンストラクターの次の初期化があります。

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' は現在のコンテキストでは使用できません

それを解決する方法はありますか?

4

3 に答える 3

11

「this」キーワードは、クラスの現在のインスタンスを参照します。コンストラクターでは、インスタンスを作成しようとしているため、インスタンスにアクセスできません...以下を試してください:

public partial class WizardPage1 : WizardPage
{
    public WizardPage1()
        : base(0, getLocalizedString(typeof(WizardPage1), "PageTitle"))
    {
    }
}
于 2013-09-26T03:58:58.403 に答える
0

@Damithはこれが機能しない理由について正しいですが、これをより簡単に処理する1つの方法は次のとおりです(実装の詳細を無視します):

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")
    {
    }
}

残念ながら、このアプローチでは、基本クラスのコードにアクセスできない場合、抽象化のレイヤーを追加する必要があります。

于 2013-09-26T04:28:55.270 に答える