【问题标题】:C# Accessing a dictionary from another class is not workingC#从另一个类访问字典不起作用
【发布时间】:2012-12-27 14:32:15
【问题描述】:

我是 C# 的新手,过去 3 天一直在努力学习。我很好奇为什么下面的代码不能正常工作?我收到以下错误:对象引用未设置为对象的实例。当我尝试调用 data.dOffsets["roomtargets"] 时。但是,调用 data.sProcessName 确实没有任何错误..

我有两个类/文件。程序.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"]);

还有 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}
            };
        }
    }

任何帮助将不胜感激!

【问题讨论】:

    标签: c# object dictionary reference


    【解决方案1】:

    您的 dOffsets 是构造函数的本地变量。你的类已经有了这个属性,所以你不需要在那里声明另一个局部变量

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

    这应该可以工作

    【讨论】:

    • 感谢您的快速而有帮助的回答!
    【解决方案2】:
            Dictionary<string, int> dOffsets = new Dictionary<string, int>()
            {
                {"roomtargets", 0x0018FA48}
            };
    

    此代码将字典初始化为构造函数中的内部变量。将其更改为:

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

    this.dOffsets 更清楚。

    【讨论】:

    • 当然!基本上我在构造函数中重新声明了相同的变量,但不再是公共变量?感谢您快速而有帮助的回复!
    • 您的变量是在构造函数范围内声明的,因此它仅在该构造函数内有效。因为变量的名称与类成员上的名称相同,所以它隐藏了该成员(在您的情况下是一个属性)。之后必须使用 this 关键字访问该属性。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-26
    • 2019-09-01
    • 1970-01-01
    • 2012-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多