[英]How do I pass arguments to a public class in C#?
如何將參數傳遞給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
}
}
如何傳遞請求的參數?
我希望寫下這樣的東西:
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"
};
通過命令行啟動應用程序時,將填充Main
方法的String[] args
參數:
/your/application/path/DoSomething.exe arg1 arg2 arg3 ...
如果要以編程方式傳遞這些參數,則必須將變量設置為公共屬性,例如:
public class DoSomething
{
public string Apple { get; set; }
public string Orange { get; set; }
public string Banana { get; set; }
// other fruits...
}
然后你可以這樣做:
public class Test
{
public static void Main(System.String[] args)
{
DoSomething ds = new DoSomething();
ds.Apple = "pie";
// do something
}
}
使用公共屬性,您可以使用自動實現的屬性開頭:
public class DoSomething
{
public string Apple {get;set;}
}
構造函數:
public class DoSomething
{
public DoSomething(String mystring) { ... }
static void Main(String[] args) {
new DoSomething(args[0]);
}
}
注意到C#在線圖書是用德語寫的。 但我確信也有英文書籍。
在您提供的示例中,您正在創建的變量在Main
方法中作用域; 它們不是類級變量。
您可以通過使它們成為類的成員來訪問它們,如下所示:
我原來的代碼片段錯了; 您的Main
方法是靜態的,因此您無法訪問實例變量。
public class DoSomething
{
public string apple;
public void Main(System.String[] args)
{
apple = args[0];
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.