简体   繁体   English

控制台C#中同一类的不同方法中公共变量的范围是什么

[英]What is the scope of public variable in different methods of a same class in Console C#

I have a class named Data that is used to retrieve a user's data我有一个名为 Data 的类,用于检索用户的数据

    class Data
    {
        public string firstName;
        public string lastName;
        public void getdata()
        {
            firstName = "ABC";
            lastName = "XYZ";
        }
        public static XDocument GetDataToXml()
        {
            var objget = new Data();
            objget.getdata();
            XDocument doc = new XDocument(
               new XElement("firstName ", objget.firstName),
               new XElement("lastName", objget.firstName));
            return doc;
        }
        public void display()
        {
            string fdata = firstName;  //i get "firstName"  value as null why????
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            var obj = new Data();
            obj.getdata();
            obj.display();
            Console.ReadLine();
        }
    }

Why do I get null value when I call disp() ,Also I just want to access the values of firstName and lastName in the GetDataToXml() even there the getData() function gets called.What is the scope of this variable in spite me assigning it as public?为什么我在调用disp()时得到空值,而且我只想访问GetDataToXml()firstNamelastName的值,即使在那里getData()函数被调用。尽管我,这个变量的范围是什么将其分配为公共?

To help you a little i have redesigned your example :为了帮助您,我重新设计了您的示例:

class Program
{
    static void Main(string[] args)
    {
        var obj = new Data();
        obj.setData("First", "Last");
        obj.GetDataToXml();
        Console.ReadLine();
    }
}

class Data
{
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public void setData(string firstName, string lastName)
    {
        FirstName = firstName;
        LastName = lastName;
    }
    public XDocument GetDataToXml()
    {
        XDocument doc = new XDocument(
           new XElement("FirstName ", FirstName),
           new XElement("LastName", LastName));
        return doc;
    }
}

Put a Breakpoint inside the GetDataToXML method and check both FirstName and LastName values.在 GetDataToXML 方法中放置一个断点并检查 FirstName 和 LastName 值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM