【问题标题】:Do anyone know why I'm getting Null exception error?有谁知道为什么我会收到 Null 异常错误?
【发布时间】:2011-07-21 12:01:37
【问题描述】:

我不断收到 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();
        }
    }
}

【问题讨论】:

    标签: c# class


    【解决方案1】:

    Values 从未分配过默认值,我认为您在分配值之前尝试访问 Values 属性。

    将您的构造函数更改为:

    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>();
    }
    

    【讨论】:

    • 哇,你明白了。它现在像微风一样工作。我将“(Hello)(myHello [1])[1])”更改为“myHello [1] [1]”,因为它给了我一些转换错误。再次感谢!
    【解决方案2】:

    你需要在这里实现getset

     public Dictionary<int, object> Values
        {
            get;
            set;
        }
    

    【讨论】:

    • 还是可以的。它是 C# 3.0 中添加的一个特性(自动属性)
    • 我明白这一点,但它返回 null 这解释了 OP 描述的内容......要么他在构造函数中为 Values 分配一些东西,要么实现它以将 get/set 映射到已定义的字典之一。 .
    • 你知道吗,你可以在这里找到某事。提问者正在做一些不完全明显或不明智的事情。
    • 谁能说说如何实现它们?它在没有实现它们的情况下运行,但为了安全起见并了解更多信息,我想知道我将如何做到这一点。
    • 抱歉 Anthony 没有正确解释它,我正在创建一个具有字典属性的对象并将这个对象传递给一个函数来修改它,这是我的意图。但是这个程序用在一个完全不同的地方,需要实现这些概念。
    猜你喜欢
    • 2018-02-10
    • 1970-01-01
    • 1970-01-01
    • 2011-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-08
    相关资源
    最近更新 更多