我用这个把头撞在墙上非常严重。我想重复使用 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/