C#从另一个类访问字典不起作用 [英] C# Accessing a dictionary from another class is not working
本文介绍了C#从另一个类访问字典不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个类/文件。 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]);
而Data.cs:
public class Data
{
public string sProcessName {get;组; }
public Dictionary< string,int> dOffsets {get;组; }
public Data()
{
sProcessName =Client;
字典< string,int> dOffsets = new Dictionary< string,int>()
{
{roomtargets,0x0018FA48}
};
}
}
任何帮助将不胜感激!
解决方案
字典< string,int> dOffsets = new Dictionary< string,int>()
{
{roomtargets,0x0018FA48}
};
此代码将字典初始化为构造函数内的内部变量。更改为:
dOffsets = new Dictionary< string,int>()
{
{ roomtargets,0x0018FA48}
};
或 this.dOffsets
清楚。
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!
解决方案
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.
这篇关于C#从另一个类访问字典不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文