C# - start /or run class
I'm new to c# but Im an advanced user in vb.net so I'm trying to bring my vb.net skills over to c# and one of the troubles I'm having is I dont know how to start a class for example
class Example {
public static void Main() {
text开发者_如何学JAVAbox1.text = "Test";
}
}
What do you mean by start a class?
In C#, you have to Instantiate the class to use it further.
Example objExample = new Example();
Starting a class is called instantiation.
Instantiating a class calls the constructor, which is one or many method(s) with the same name as the class with no return type.
public class Example
{
//attributes
public string MyLocalString = "";
public static string MySharedString = "";
//constructor(s)
public Example()
{
//code
}
//method(s)
public string ExampleMethod()
{
//code
}
public void ExampleFunctionMethod()
{
//code
}
public string ExampleProcedureMethod()
{
//code
return "";
}
public static void ExampleSharedFunctionMethod()
{
//code
}
public static string ExampleSharedProcedureMethod()
{
//code
return "";
}
}
...and then you instantiate it like this:
Example o = new Example();
o.ExampleFunctionMethod();
string s = o.ExampleProcedureMethod();
Example.ExampleSharedFunctionMethod();
string s = Example.ExampleSharedProcedureMethod();
Unless you mean the main method in a class, which is the starting point of a program.
public static void main(string[] args)
{
//code
}
You have to select the start class in solution explorer or set the start class in the properties tab before pressing run.
After that, most of the code is the same as VB.
There are pros and cons to switching from VB to C#, just as there are when switching from C# to VB.
You might find that C# is less flexible when it comes to declaring variables of the same name e.g. within a switch (equivalent to select) statement. So if you wish to use a variable with the same name over multiple cases then you are forced to declare your variables outside the switch statement declaration. This is because each case isn't isolated as they are in VB. Whether this is a good or bad thing is entirely down to personal preference.
My personal opinion is that it doesn't matter which one is chosen, with neither being superior than the other (despite whatever advocates of each language will tell you). All you have to remember that there are more differences between VB and C# than syntax, and through practice it should become second-nature to flick between the two mind-sets.
精彩评论