简体   繁体   中英

NullReferenceException when accessing a property outside of the constructor

In this class, I am setting elp to ElType in the constructor.

I can access properties of elp fine when in the constructor (the // ... bit is where I'm accessing elp 's properties), but when I try to access elp in another method - ucp() - my program crashes with NullReferenceException .

I can't figure out what I'm doing wrong here, although it would probably be something pretty straight forward.

[Serializable]
public class ElBase : RectangleNode
{
    public ElementParameters elp;

    public ElBase(ElementParameters ElType)
    {
        this.elp = ElType;

        // ...
    }

    private void ucp()
    {
        int i = 0;

        if (this.elp.HasInput)
        {
            // ...
        }
    }

Either:

  1. elp is set to null, possibly even in the constructor if there's not a null check there
  2. The HasInput property getter is throwing the NullReferenceException based on code inside it.
  3. Oh dear : elp is a publicly accessible field . Anything can set it to null. :o This should be number 1, but I looked straight past it since no one makes publicly accessible fields, hence it's never a problem.

在不查看调用代码的情况下不能说太多,但看起来传递给构造函数的ElementParameters是NULL还是未初始化。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM