c# - 将变量从 Main 函数传递到另一个 C# 类

标签 c# program-entry-point

我用这个把头撞在墙上非常严重。我想重复使用 C# 控制台应用程序中的几个变量。但是,我不能在我的生活中重新使用另一个类中的变量。我希望您能提供任何帮助或指点 - 我已经搜索了很长时间,但我完全被难住了。

编辑:是的,变量在我的 Main 函数中。抱歉遗漏了这一点。

编辑:下面经过大量编辑的代码。我想在另一个类中重复使用的变量值在中间。还有更多,但是这 3 个应该足够了。感谢您的帮助!!!

public static class MyApp
    {
        static void Main(string[] args)
        {
            // loads XML doc
            foreach (XmlNode node in nodes)
            {
            try
                {
                    // does a bunch of stuff

                    // Parses variables from REST API

                    XDocument docdetailxml = XDocument.Parse(xmldoc);

                    XNamespace ns = docdetailxml.Root.GetDefaultNamespace();

                    var buid = docdetailxml.Root.Element(ns + "busid").Value;
                    var bname = docdetailxml.Root.Element(ns + "busname").Value;
                    var bcount = docdetailxml.Root.Element(ns + "buscount").Value;

                    // Invoke SQL connection string

                    // Trigger Stored Procedure and write values to database

                    // If needed, trigger email notification

                    // Close connections
                }
                catch (Exception e)
                {

                    Console.WriteLine("Error encountered: " + e.Message);

                    // Exit the application
                    System.Environment.Exit(1);

                }
                finally
                {
                    // Exit the application
                    // System.Environment.Exit(0);
                }

            }

        }

        private static void GetConnectionString()
        {
            throw new NotImplementedException();
        }

        private static void GetConnectionStrings()
        {
            throw new NotImplementedException();
        }
    }
}

最佳答案

你应该定义公共(public)属性(property)或公共(public)领域

public class Student
{
public string Name {get;set;}
}

当你想传递值时,你可以将这个值分配给属性

Student st = new Student(); 
st.Name = "your value";

或者您也可以使用类构造函数。

关于c# - 将变量从 Main 函数传递到另一个 C# 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8709315/

相关文章:

c# - 使用 API 管理 i18n 的最佳做法是什么?

java.lang.NoSuchMethodError : main error in simple java program

java - 什么是 stub 主要方法?

hadoop - 运行示例 wordcount "Exception in thread "main"

c# - 在函数参数中传递 List<int> 并包含超过 10 条 lac 记录?

c# - Linq 谓词查询结果不适用于进一步的 Linq Join

java - Jar Maker——哪个是主要类别?

c++ - 具有多个项目的 visual studio 解决方案无法编译

c# - 如何将命名空间检索到字符串 C#

c# - 列表正在复制同一行