C#面向对象初步创建类的对象

2025-10-09 09:16:11

1、打开VS2015,在‘ObjectLearn’解决方案下,新建一个控制台项目

‘ObjectLearn1’

C#面向对象初步创建类的对象

2、在项目‘ObjectLearn1’下,新建一个类‘animal’

C#面向对象初步创建类的对象

3、在新建的‘animal.cs’类中写如下代码:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace ObjectLearn

{

    class animal

    {

        public string _name;

        public int _age;

        public void eat()

        {

            System.Console.WriteLine("I am hungry");

        }

            

    }

}

注意几点

1 命名空间名要与Program.cs文件的一致,不然无法识别

2 animal类的字段及方法要public,不然无法外部无法访问

C#面向对象初步创建类的对象

4、在Program.cs文件写代码实例化animal类,并通过对象调用方法如下:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace ObjectLearn

{

    class Program

    {

        static void Main(string[] args)

        {

            animal ani = new animal();

            ani._name = "xiaohong";

            ani._age = 25;

            ani.eat();

            System.Console.ReadKey();

        }

    }

}

C#面向对象初步创建类的对象

5、在项目名‘ObjectLearn1’右键,在弹出菜单,选择设为启动项目

C#面向对象初步创建类的对象

6、点击vs2015上方的启动按钮,运行程序

C#面向对象初步创建类的对象

7、程序运行,弹出命令行窗口,打印出

I am hungry

命令行窗口不会消失,是因为

System.Console.ReadKey();

不然程序会一闪而过

C#面向对象初步创建类的对象

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢