如何在 C# 中将参数传递给公共(public)类。 我是 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
}
}
如何传递请求的参数?
我希望这样写:
DoSomething ds = new DoSomething();
ds.apple = "pie";
但这失败了。
最佳答案
首先,让我们在您的版本上加上注释,然后继续您可能想要的内容。
// 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()
}
以下是您可能需要的类定义:
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;
}
}
然后您可以像下面这样创建/操作类。在每种情况下,实例都将以 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"
};
关于c# - 如何将参数传递给 C# 中的公共(public)类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9100144/