【发布时间】:2012-02-24 09:19:02
【问题描述】:
如何将参数传递给 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";
但这失败了。
【问题讨论】:
-
您是否在 DoSomething 类中声明了“apple”变量?
-
您使用的方法
public static void Main(System.String[] args)通常用于接受命令行参数。 -
为了帮助您移动谷歌搜索,您希望在类上设置属性值,而不是向类传递参数(在构造函数之外,这没有意义 - 类方法获取提供的变量,而不是类本身)。
-
如果你想使用类而不是取出主方法并为苹果橙香蕉等创建属性..
-
@mmcglynn:旁注 - 您不会在 C# 中“将参数传递给类”(甚至不确定可以使用哪种语言),而是“将参数传递给方法”,其中 method 是某个类的静态方法,如
DoSomething.Main("string_arg")或只是类myInstance.Method(42)的成员。
标签: c# .net arguments console-application