开发者

What wrong with Dictionary in property of class?

Why is this code not working?

public class A   
{
   public Dictionary<int, string> dic { get; set; }   
}

class Program   
{
    public static v开发者_如何学运维oid Main()
    {
        A a = new A();
        a.dic.Add(1, "a");
    }   
}

Error: System.NullReferenceException was unhandled Message=Object reference not set to an instance of an object.


You haven't initialized the property, so the value of a.dic is null (the default for any reference type).

You'd need something like:

a.dic = new Dictionary<int, string>();

... or you could initialize it in the constructor.

On the other hand, it's rarely a good idea to have such direct access to the inner workings of a class - you basically have no encapsulation here.


Dictionary is a reference type. It's default value is null. There's no "new Dictionary" anywhere in your program; there probably should be.


    public class A
    { public Dictionary dic;

A()

{

dic = new Dictionary();
}

    }

    class Program
    { public static void Main() { A a = new A(); a.dic.Add(1, "a");

    }   

    }


Change the definition of A to something like this:

public class A
{
    public Dictionary<int, string> dic { get; set; }

    public A()
    {
        dic = new Dictionary<int, string>();
    }
}

The key point is that you need to initialize the "dic" property before you can use it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜