C#类 – 基本示例
发布时间:2020-12-16 00:22:17 所属栏目:百科 来源:网络整理
导读:这基本上是我第一次尝试理解C#中的类.我在互联网上经历过几个教程,但是我最想念的东西和我还没有找到的东西,就是一个简单的好例子. 我知道我的基本程序应该是什么样子,我将非常感谢你的帮助: using System;namespace Introduction_to_classes{ class Person
这基本上是我第一次尝试理解C#中的类.我在互联网上经历过几个教程,但是我最想念的东西和我还没有找到的东西,就是一个简单的好例子.
我知道我的基本程序应该是什么样子,我将非常感谢你的帮助: using System; namespace Introduction_to_classes { class Person { int Age; string Name; int DateOfBirth() { return 2013 - Age; } } class Program { public static void Main() { Person Mother = new Person(35,Alice); Person Son = new Person(12,Johny); Mother.Name = "Lucy"; // Just changing the value afterwards if(Mother.Age > Son.Age) { int year = Mother.DateOfBirth(); Console.WriteLine("Mom was born in {0}.",year); } Console.ReadLine(); } } } 这只是一个想法,它绝对不起作用.但最重要的是,如果你能够将其改正为工作实例,它将对我有所帮助…… 解决方法class Person { public int Age { get; set; } public string Name { get; set; } public Person(int age,string name) { Age = age; Name = name; } public int DateOfBirth() { return 2013 - Age; } } class Program { public static void Main() { Person Mother = new Person(35,"Alice"); Person Son = new Person(12,"Johny"); Mother.Name = "Lucy"; // Just changing the value afterwards if (Mother.Age > Son.Age) { int year = Mother.DateOfBirth(); Console.WriteLine("Mom was born in {0}.",year); } } } 一些有用的链接:properties,constructor (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |