简体   繁体   中英

How to use properties in C#

The error I receive when I create an Object of Class1 and attempt to run this property using Main is:

"Error 1 Non-invocable member 'ConsoleApplication1.Class1.X_ValueProperty' cannot be used like a method. C:\\Users\\Qosmio\\AppData\\Local\\Temporary Projects\\ConsoleApplication1\\Program.cs 14 15 ConsoleApplication1"

I understand this error perfectly well. IE, you can't run a property as if it's a method, but it seems the presenter of the video I learned this from is able to do so. (Around the 1:20 mark.)

In the Main method, it seems he calls the object, then the property, and inputs a value where as I get the error.

Can anyone identify what I'm doing wrong?

class Class1
{
    int x;

    public int X_ValueProperty
    {
        set {
            if (value <= 0)
            {
                throw new Exception("Value cannot be zero or less than zero.");
            }
            this.x = value;
            }
        get 
        {
            return this.x;
        }
    }
}

Here is where the error comes in:

class Program
{
    static void Main(string[] args)
    {
        Class1 z= new Class1();

        //Error--> z.X_ValueProperty();


    }   
}

You must be invoking the property something like this:-

Class1 cls = new Class1();
cls.X_ValueProperty();

Please notice its a property and not a method, you can set or get the value of a property of a class. Please read about Properties properly first.

You can set\\get values like this:-

cls.X_ValueProperty = 25;
int x = cls.X_ValueProperty;

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