c# - An object reference is required for the non-static field -
i have followed this tutorial , try use access database in c# console application.
i have 2 classes:
class ac { oledbconnection connection; oledbcommand command; private void connectto() { connection = new oledbconnection(@"provider=microsoft.ace.oledb.15.0;data source=d:\info\csharp\socket\ef\accesstest\accesstest\bin\debug\database.accdb;persist security info=false"); command = connection.createcommand(); } public ac() { connectto(); } public void insert(string a, string b) { try { command.commandtext = "insert persons (nname, nnamee) values (\"" + + "\", \"" + b + "\");"; command.commandtype = system.data.commandtype.text; connection.open(); command.executenonquery(); } catch (exception) { throw; } { if (connection != null) { connection.close(); } } } }
and,
namespace accesstest { public class mainclass { ac f = new ac(); public static void main() { f.insert("ab", "ac"); console.writeline("\n\npress enter close..."); console.readline(); } } }
and "an object reference required non-static field, method, or property 'accesstest.mainclass.f'". try remove static from, don't work, main must pe static.
any ideas me ? thank !
you can't refer instance variable f without object reference in static context.
as per msdn,the main method entry point of program; program control starts , ends.
- main declared inside class or struct. main must static , should not public. (in earlier example, receives default access of private.) enclosing class or struct not required static.
- main can either have void or int return type.
- the main method can declared or without string[] parameter contains command-line arguments. when using visual studio create windows forms applications, can add parameter manually or else use environment class obtain command-line arguments. parameters read zero-indexed command-line arguments. unlike c , c++, name of program not treated first command-line argument.
Comments
Post a Comment