简体   繁体   中英

Why am I getting an exception with the following code?

I have a property defined in an interface as:

 Boolean IsBusy { get; }

It is implemented in the class as:

private Boolean _isBusy = false;
public Boolean IsBusy
    {
        get
        {
            return this._isBusy;
        }

        private set
        {
            if (this._isBusy != value)
            {
                this._isBusy = value;
                this.OnPropertyChanged("IsBusy");
            }
        }
    }

Then when I run the app, I always get following kind of error when check IsBusy value in constructor:

'IsBusy' threw an exception of type 'System.NullReferenceException' bool {System.NullReferenceException}

I can't figure it out. If I change all Boolean to bool , get same error.

How can I fix it?

You fix it by checking whether OnPropertyChanged is null before calling it, assuming OnPropertyChanged is an event or a delegate variable (you haven't made this clear). This has nothing to do with bool or Boolean , which are equivalent (assuming that Boolean is resolved to System.Boolean ).

I can't see any other reason it would throw NullReferenceException - although it would really help you could clarify whether you were calling the getter or the setter at the time it threw the exception. A short but complete example would be even more helpful.

bool只是Boolean的语法快捷方式

boolBoolean都在编译时评估相同的东西。

none. Boolean is what the .net CLI uses to represent a true/false value. bool is what c# uses.

  1. bool is a C# alias for the struct System.Boolean . They are the same.
  2. Your problem probably is that this.OnPropertyChanged is unassigned. This is completely unrelated to bool vs Boolean .

C# contains aliase for all the native types. String for string, Int32 for int, etc. there is no difference with which you use:

String vs string in C#

Boolean cannot be NULL, so you are likely getting an error because of something in OnPropertyChanged.

The bool keyword is just a type alias for the Boolean keyword.

Just the same as int is an alias for Int32 .

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