0

I am getting an error "An object reference is required for the non-static field, method, or property 'Excel1.Program.GetAllTemplateNames(string, string)" I know this is pretty silly but I am quite new to C# and could do with some assistance in debugging this code. Is it even possible to call a static function from a Main function? Am having these doubts.

4

5 に答える 5

4

は静的であるため、このクラスのインスタンス ( ) がなければ、そこからProcessInputインスタンス (非静的) メソッドを呼び出すことはできません。GetAllTemplateNamesProgram

したがって、静的にするか、非静的GetAllTemplateNamesにする必要があります。静的な場合は不可能ないくつかのインスタンス変数にアクセスする必要があるためProcessInput、2 番目のオプションを選択します。GetAllTemplateNames

の署名をProcessInput次のように変更します (省略されていることに注意してくださいstatic)。

public void ProcessInput(String strRetVal, String strFunctionName, /*String strParamCount,*/ String strParam1, String strParam2, String strParam3, String strParam4)

このメソッドの呼び出しを次のように変更する必要もありますmain

var p = new Program();  // create an instance
p.ProcessInput(strRetVal, strFunctionName, /*strParamCount,*/ strParam1, strParam2, strParam3, strParam4);

MSDN: 静的

于 2012-06-18T09:50:58.570 に答える
3

クラスのインスタンスなしで他の静的メソッドから呼び出すことができるようにする場合は、GetAllTemplateNamesメソッドを作成する必要があります。static

public static void GetAllTemplateNames(String strParam, String strRetVal)

これはまた、このメソッドが使用するフィールド (また静的templateClientでなければならない) も意味します。taskClient

または別の可能性は、包含クラスのインスタンスを作成することです:

new Program().GetAllTemplateNames(strParam1, strRetVal);
于 2012-06-18T09:45:20.647 に答える
2

この行を変更

      GetAllTemplateNames(strParam1, strRetVal);

      new Program().GetAllTemplateNames(strParam1, strRetVal);

またはメソッドを静的にします。

于 2012-06-18T09:45:48.057 に答える
2

この問題は、回線、およびまたはGetAllTemplateNames(strParam1, strRetVal);へのその他の呼び出しで発生しています。GetAllTemplateNames()ReturnAllTemplateNames()

これらのメソッドは静的ではありませんが、静的メソッドから呼び出しています! のような静的メソッドから呼び出すには、それらを静的にするか、それらを含むクラスのインスタンスを作成する必要がありますmain()

于 2012-06-18T09:46:20.613 に答える
1

メイン関数は静的であるため、ProcessInput を呼び出すことができます。ただし、静的関数から非静的関数を呼び出すことはできません。GetAllTemplateNames は静的関数でなければなりません。

于 2012-06-18T09:55:47.147 に答える