//命名空间
namespace Common;
//类
internal class Program
{
//程序入口
static void Main(string[] args)
{
Person person = new Person();
//使用属性赋值
person.Name = "流川楓";
person.Age = 16;
person.Sex = (int)Sex.M;
//結果:名前:流川楓、年齢:16、性別:1
person.showPersonInfo();
//使用属性取值
string name = person.Name;
int age = person.Age;
//結果:名前:流川楓、年齢:16
Console.WriteLine("名前:{0}、年齢:{1}", name, age);
/************************************************************/
//匿名类型
var tmp = new Person();
var num = 23;
//結果:tmpのデータ型:Common.Person、numのデータ型:System.Int32
Console.WriteLine("tmpのデータ型:{0}、numのデータ型:{1}", tmp.GetType(), num.GetType());
}
//enum类型
public enum Sex
{
F = 0, M = 1
}
}
/// <summary>
/// Person类
/// </summary>
internal class Person
{
private string name;
private int age;
private int sex;
//构造函数的名字要与类同名,没有返回值。
//当没有定义构造函数时,类会默认创建一个无参的构造函数
public Person() { }
/// <summary>
/// name属性声明
/// </summary>
public string Name
{
//get,set可以简写
get;set;
}
/// <summary>
/// age属性声明
/// </summary>
public int Age
{
get { return age; }
set
{
if(value > 0)
{
age = value;
}
}
}
/// <summary>
/// sex属性声明
/// </summary>
public int Sex
{
//属性可以设置访问权限符,未设定时,默认和属性声明同级
private get { return sex; }
set { sex = value; }
}
/// <summary>
/// 信息显示
/// </summary>
public void showPersonInfo()
{
Console.WriteLine("名前:{0}、年齢:{1}、性別:{2}", this.name, this.age, this.sex);
}
}
C# 属性、匿名类型
于 2023-04-12 11:49:04 首次发布