C# Accessing a dictionary from another class is not working

偶尔善良 提交于 2019-12-24 00:49:35

问题


I'm fairly new to C# and have been trying to learn for the last 3 days. I am curious as to why the below code is not working properly? I get the following error: Object reference not set to an instance of an object. when I try to call data.dOffsets["roomtargets"]. However, calling data.sProcessName does work without any error..

I have two classes/files. The program.cs:

class Program
    {
        public static Data data = new Data();

        static void Main(string[] args)
        {
            Console.WriteLine("data.sProcessName: {0}", data.sProcessName);
            Console.WriteLine("data.dOffsets[\"roomtargets\"]: {0}", data.dOffsets["roomtargets"]);

And the Data.cs:

public class Data
    {
        public string sProcessName { get; set; }
        public Dictionary<string, int> dOffsets { get; set; }

        public Data()
        {
            sProcessName = "Client";

            Dictionary<string, int> dOffsets = new Dictionary<string, int>()
            {
                {"roomtargets", 0x0018FA48}
            };
        }
    }

Any help would be greatly appreciated!


回答1:


        Dictionary<string, int> dOffsets = new Dictionary<string, int>()
        {
            {"roomtargets", 0x0018FA48}
        };

This code initialize a dictionary as an inner variable within the constructor. Change it to:

        dOffsets = new Dictionary<string, int>()
        {
            {"roomtargets", 0x0018FA48}
        };

or this.dOffsets to make it more clear.




回答2:


Your dOffsets is local to the constructor. Your class already has that property, so you don't need declare another local variable there

public Data()
{
    sProcessName = "Client";

    dOffsets = new Dictionary<string, int>()
    {
        {"roomtargets", 0x0018FA48}
    };
}

this should work



来源:https://stackoverflow.com/questions/14304770/c-sharp-accessing-a-dictionary-from-another-class-is-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!