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.
5 に答える
は静的であるため、このクラスのインスタンス ( ) がなければ、そこからProcessInput
インスタンス (非静的) メソッドを呼び出すことはできません。GetAllTemplateNames
Program
したがって、静的にするか、非静的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);
クラスのインスタンスなしで他の静的メソッドから呼び出すことができるようにする場合は、GetAllTemplateNames
メソッドを作成する必要があります。static
public static void GetAllTemplateNames(String strParam, String strRetVal)
これはまた、このメソッドが使用するフィールド (また静的templateClient
でなければならない) も意味します。taskClient
または別の可能性は、包含クラスのインスタンスを作成することです:
new Program().GetAllTemplateNames(strParam1, strRetVal);
この行を変更
GetAllTemplateNames(strParam1, strRetVal);
に
new Program().GetAllTemplateNames(strParam1, strRetVal);
またはメソッドを静的にします。
この問題は、回線、およびまたはGetAllTemplateNames(strParam1, strRetVal);
へのその他の呼び出しで発生しています。GetAllTemplateNames()
ReturnAllTemplateNames()
これらのメソッドは静的ではありませんが、静的メソッドから呼び出しています! のような静的メソッドから呼び出すには、それらを静的にするか、それらを含むクラスのインスタンスを作成する必要がありますmain()
。
メイン関数は静的であるため、ProcessInput を呼び出すことができます。ただし、静的関数から非静的関数を呼び出すことはできません。GetAllTemplateNames は静的関数でなければなりません。