Грамотное использование переменных, get() и set() - C#

Узнай цену своей работы

Формулировка задачи:

Подскажите как грамотней использовать переменные в классе и вызывать их из других классов? И в чем разница:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace Test
{
    class Car
    {
 
        public int speed{get;set;}
 
        public Car()
        {
            speed = 100;
            ......
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace Test
{
    class Car
    {
 
        public int speed;
 
        public Car()
        {
            speed = 100;
            .....
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace Test
{
    class Car
    {
 
        private int _speed;
 
        public int speed
        {
            get
            {
                return _speed;
            }
            set
            {
                _speed = value;
            }
        }
 
        public Car()
        {
            _speed = 100;
            .....
        }
    }
}

Решение задачи: «Грамотное использование переменных, get() и set()»

textual
Листинг программы
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace Test
{
    class MainClass
    {
        public static void Main()
        {
            Car car = new Car();
            car.speed = 1;
            Console.WriteLine(car.speed);
            Console.ReadKey();
        }
    }
}

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

9   голосов , оценка 4 из 5