个性化阅读
专注于IT技术分析

C#属性

C#Properites没有存储位置。 C#属性是字段的扩展,并且像字段一样进行访问。

这些属性具有用于设置,获取或计算其值的访问器。

C#属性的用法

  1. C#属性可以是只读或只写的。
  2. 在C#属性中设置值时,我们可以拥有逻辑。
  3. 我们将类的字段设为私有,这样就不能直接从类外部访问字段。现在我们被迫使用C#属性来设置或获取值。

C#属性示例

using System;
   public class Employee
    {
        private string name;

        public string Name
        {
            get
            {
                return name;
            }
            set
            {
                name = value;
            }
        }
   }
   class TestEmployee{
       public static void Main(string[] args)
        {
            Employee e1 = new Employee();
            e1.Name = "Sonoo Jaiswal";
            Console.WriteLine("Employee Name: " + e1.Name);

        }
    }

输出:

Employee Name: Sonoo Jaiswal

C#属性示例2:在设置值时具有逻辑

using System;
   public class Employee
    {
        private string name;

        public string Name
        {
            get
            {
                return name;
            }
            set
            {
                name = value+" srcmini";
                
            }
        }
   }
   class TestEmployee{
       public static void Main(string[] args)
        {
            Employee e1 = new Employee();
            e1.Name = "Sonoo";
            Console.WriteLine("Employee Name: " + e1.Name);
        }
    }

输出:

Employee Name: Sonoo srcmini

C#属性示例3:只读属性

using System;
   public class Employee
    {
        private static int counter;

        public Employee()
        {
            counter++;
        }
        public static int Counter
        {
            get
            {
                return counter;
            }
         }
   }
   class TestEmployee{
       public static void Main(string[] args)
        {
            Employee e1 = new Employee();
            Employee e2 = new Employee();
            Employee e3 = new Employee();
            //e1.Counter = 10;//Compile Time Error: Can't set value

            Console.WriteLine("No. of Employees: " + Employee.Counter);
        }
    }

输出:

No. of Employees: 3
赞(0)
未经允许不得转载:srcmini » C#属性

评论 抢沙发

评论前必须登录!