简体   繁体   中英

Object reference required for a non-static field

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.

Since ProcessInput is static you cannot call the instance(non-static) method GetAllTemplateNames from there without having an instance of this class ( Program ).

So you either need to make GetAllTemplateNames also static or you need to make ProcessInput non-static. I would choose the second option since GetAllTemplateNames needs to access some instance variables which is impossible when it's static.

So change the signature of ProcessInput in the following way(note the omited static ):

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

now you also need to change the call of this method in main to:

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

MSDN: static

You should make the GetAllTemplateNames method static if you want to be able to call it from other static methods without an instance of a class:

public static void GetAllTemplateNames(String strParam, String strRetVal)

This also means that the fields that this method uses ( templateClient and taskClient must also be static)

or another possibility is to create an instance of the containing class:

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

Change this line

      GetAllTemplateNames(strParam1, strRetVal);

to

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

or make the method static.

The problem is occurring on the line GetAllTemplateNames(strParam1, strRetVal); , and any other calls to GetAllTemplateNames() or ReturnAllTemplateNames() .

These methods are not static, yet you are calling them from a static method! You'll need to make them static, or create an instance of their containing class in order to call them from a static method like main() .

The main function is static, that's why you can call ProcessInput. However, you can't call a non-static function from a static one : GetAllTemplateNames has to be a static function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM