c# - 如何将参数传递给 C# 中的公共(public)类?

标签 c# .net arguments console-application

如何在 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/

相关文章:

用于调用函数的 Python 管道符

c# - 禁用 RichTextBox 自动滚动

c# - 默认情况下,子窗体是否在主窗体的同一线程上运行?

.net - Exchange Web 服务 : Where do the deleted appointments go?

python - 如何比较两个文件并查找之间最大的单词

C++如何? function_x(新对象 1)

c# - C# 中的 System.Linq.Expressions 是干什么用的?

c# - 使用 ContinueWith 时,Hangfire 中排队的子作业的优先级是什么?

.net - 如何在 C++ 中使用 MethodInvoker?

c# - 方法调用公共(public)/私有(private)成员或方法最佳实践 - C#.NET