我继续得到Null异常 . 我在程序中实例化了myHello,但它仍然给了我这个错误 . 提前致谢 .
class Hello
{
public Dictionary<int, string> one;
public Dictionary<int, ushort> two;
public Dictionary<int, bool> three;
public Hello()
{
this.one = new Dictionary<int, string>();
this.two = new Dictionary<int, ushort>();
this.three = new Dictionary<int, bool>();
}
public Dictionary<int, object> Values
{
get;
set;
}
public object this[int index]
{
get
{
return this.Values[index];
}
set
{
this.Values[index] = value;
}
}
}
class Program
{
public static void myfun(ref Hello hu)
{
hu[0] = "Hello";
hu[1] = 25;
hu[2] = true;
}
static void Main(string[] args)
{
try
{
//Program myprog = new Program();
var myHello = new Hello[2];
myHello[0] = new Hello();
myHello[1] = new Hello();
myHello[1][1] = 2;
myfun(ref myHello[1]);
Console.WriteLine("" + (Hello)(myHello[1])[1]);
Console.ReadKey();
}
catch (NullReferenceException ex)
{
Console.WriteLine(ex.Message);
Console.ReadKey();
}
}
}
2 回答
永远不会为
Values
分配默认值,我认为您在分配值之前尝试访问Values
属性 .将构造函数更改为:
你需要在这里实现
get
和set
: