mmc*_*ynn 2 .net c# arguments console-application
如何将参数传递给C#中的公共类.我是C#的新手,所以请原谅n00b问题.
鉴于此示例类:
public class DoSomething
{
public static void Main(System.String[] args)
{
System.String apple = args[0];
System.String orange = args[1];
System.String banana = args[2];
System.String peach = args[3];
// do something
}
}
Run Code Online (Sandbox Code Playgroud)
如何传递请求的参数?
我希望写下这样的东西:
DoSomething ds = new DoSomething();
ds.apple = "pie";
Run Code Online (Sandbox Code Playgroud)
但这失败了.
首先,让我们用笔记点击你的版本,然后继续你想要的.
// Here you declare your DoSomething class
public class DoSomething
{
// now you're defining a static function called Main
// This function isn't associated with any specific instance
// of your class. You can invoke it just from the type,
// like: DoSomething.Main(...)
public static void Main(System.String[] args)
{
// Here, you declare some variables that are only in scope
// during the Main function, and assign them values
System.String apple = args[0];
System.String orange = args[1];
System.String banana = args[2];
System.String peach = args[3];
}
// at this point, the fruit variables are all out of scope - they
// aren't members of your class, just variables in this function.
// There are no variables out here in your class definition
// There isn't a constructor for your class, so only the
// default public one is available: DoSomething()
}
Run Code Online (Sandbox Code Playgroud)
以下是您可能想要的类定义:
public class DoSomething
{
// The properties of the class.
public string Apple;
public string Orange;
// A constructor with no parameters
public DoSomething()
{
}
// A constructor that takes parameter to set the properties
public DoSomething(string apple, string orange)
{
Apple = apple;
Orange = orange;
}
}
Run Code Online (Sandbox Code Playgroud)
然后你就可以创建/操作类,如下所示.在每种情况下,实例最终将以Apple ="foo"和Orange ="bar"结束
DoSomething X = new DoSomething("foo", "bar");
DoSomething Y = new DoSomething();
Y.Apple = "foo";
Y.Orange = "bar";
DoSomething Z = new DoSomething()
{
Apple = "foo",
Orange = "bar"
};
Run Code Online (Sandbox Code Playgroud)
通过命令行启动应用程序时String[] args,将Main填充方法的参数:
/your/application/path/DoSomething.exe arg1 arg2 arg3 ...
如果要以编程方式传递这些参数,则必须将变量设置为public Properties,例如:
public class DoSomething
{
public string Apple { get; set; }
public string Orange { get; set; }
public string Banana { get; set; }
// other fruits...
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以执行以下操作:
public class Test
{
public static void Main(System.String[] args)
{
DoSomething ds = new DoSomething();
ds.Apple = "pie";
// do something
}
}
Run Code Online (Sandbox Code Playgroud)