zoukankan      html  css  js  c++  java
  • c#基础知识第十节

    属性

    属性是用来操作表量

    自动属性

    当不需要对字段进行控制时,我们可以使用自动属性

    public  数据类型 属性名

    {

      get;

      set;

    }

    class Student
    {
    private string name;
    public string Name
    {
    get
    {
    return name;
    }
    set
    {
    name = value;
    }
    }
    //定义只读属性
    private string degree="本科";
    public string Degree
    {
    get
    {
    return degree;

    }
    }
    //给属性赋值时对属性进行验证
    private int age;
    public int Age
    {
    get
    {
    return age;
    }
    set
    {
    if (value < 0)
    {
    Console.WriteLine("年龄不合法");
    }
    else
    {
    age = value;
    }
    }
    }
    //定义自动属性
    public string Sex
    {
    get;
    set;
    }
    //定义自我介绍的方法
    public void Introduce()
    {
    Console.WriteLine("大家好,我叫"+Name+",学历:"+Degree+",年龄:"+Age+",性别:"+Sex);
    }
    }
    class Program
    {
    static void Main(string[] args)
    {
    Student s = new Student();
    s.Name = "张三";
    s.Age = 20;
    s.Sex = "男";
    s.Introduce();
    Console.ReadKey();
    }
    }

    构造方法:创建对象时自动调用

    构造方法的定义

    1.、方法名与类名相同。

    2、在方法名的前面没有返回值的类型。

    3、在方法中不能使用return语句返回一个值。

    构建方法的重载

    class person
    {
    private string name;
    private string Sex;
    //构建方法的重载
    public person (string conName)//一个参数的构造方法
    {
    name = conName;
    }
    public person (string conName, string conSex) //两个参数的构造方法
    {
    name = conName;
    Sex = conSex;
    }
    //定义自我介绍的方法
    public void Introuduce()
    {
    Console.WriteLine("大家好,我叫:"+name+",性别:"+Sex);
    }
    }

    class Program
    {
    static void Main(string[] args)
    {
    person p = new person("张三","男");
    p.Introuduce();
    Console.ReadKey();

    }
    }

  • 相关阅读:
    [Codeforces #494] Tutorial
    [BZOJ 3223] 文艺平衡树
    [P2698][USACO12MAR]花盆Flowerpot
    [Atcoder Regular Contest 061] Tutorial
    [BZOJ 1855] 股票交易
    [BZOJ 1076] 奖励关
    [BZOJ 2298] Problem A
    数据库三大范式
    mybatis插件机制原理
    Mybatis有哪些执行器?
  • 原文地址:https://www.cnblogs.com/zhang1997/p/7661681.html
Copyright © 2011-2022 走看看