Do anyone know why I'm getting Null exception error?
I keep on getting Null exception. I instantiated myHello insi开发者_如何转开发de program and still it gives me this error. Thanks in advance.
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();
}
}
}
Values
is never assigned a default value and I think you are trying to access Values
property before assigning a value.
Change your constructor to:
public Hello()
{
this.one = new Dictionary<int, string>();
this.two = new Dictionary<int, ushort>();
this.three = new Dictionary<int, bool>();
this.Values = new Dictionary<int, object>();
}
you need to implement get
and set
here:
public Dictionary<int, object> Values
{
get;
set;
}
精彩评论