目录
一、字段
1.认识字段和属性
2.初始化字段
二、特性
1.特性的基础
2.特性的自定义和使用
三、继承
1.多继承
2.重写父类和增加子类方法
四、多态
一、字段
1.认识字段和属性
public class Test
{
public int field //我是字段
public int property { get; set; }//我是属性
}
2.初始化字段
public class Program
{
public class Test
{
public int value { get; set; }//入参
public int valueadd { get => value+1; }//入参+1 (该字段只能读不能写)
public List<int> valuelist { get; set; } = new List<int>();//必须对其初始化,否则将无法遍历,赋值(因为valuelist=null)
}
static void Main(string[] args)
{
var test = new Test { value = 5,valuelist = {1,2,3}};
Console.WriteLine($"{test.value},{test.valueadd}");
foreach (var item in test.valuelist)
{
Console.WriteLine($"数字列表:{item}");
}
// 输出:
// 5,6
// 数字列表:1
// 数字列表:2
// 数字列表:3
}
}
二、特性
1.特性的基础
1.特性定义:特性是可以标注在【类、方法、枚举等】的标签信息(可以理解为一种特殊的注释,特殊在这些注释可以由程序获取)
2.特性作用:我们可根据【类、方法、枚举等】获取其标签信息,用以其他操作
3.实际应用:各大ORM框架的Table特性,你想查某个实体的对应表,ORM会获取这个实体的Table特性拼SQL查,查完后再反射回实体
举个例子:
以上Topic类的字段使用了freesql的Column特性,类型为decimal的属性接受两个入参,拼接SQL时候就会生成:
SELECT CAST(Amount AS decimal(10,2)) FROM Topic
如果不加特性,SQL应该是:
SELECT Amount FROM Topic
2.特性的自定义和使用
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property)]
public class DataEntityAttribute : Attribute
{
public string Description { get; }
public DataEntityAttribute(string description)
{
Description = description;//【Flag】入参存进Description中,可通过attribute.Description访问存入的内容
}
}
// 使用特性
[DataEntity("这是一个用户数据实体")]
public class User
{
[DataEntity("属性特性名称")]
public string Name { get; set; }
public int Age { get; set; }
}
public class Program
{
public static void Main()
{
// 获取DataEntityAttribute特性下类的标注
DataEntityAttribute attribute = (DataEntityAttribute)Attribute.GetCustomAttribute(typeof(User), typeof(DataEntityAttribute));
var description_class = attribute?.Description;//【Flag】访问特性的内容
// 获取DataEntityAttribute特性下属性的标注
DataEntityAttribute attribute2 = (DataEntityAttribute)Attribute.GetCustomAttribute(typeof(User).GetProperty("Name"), typeof(DataEntityAttribute));
var description_property = attribute2?.Description;//【Flag】访问特性的内容
Console.WriteLine(description_class+" "+description_property);//输出:这是一个用户数据实体 属性特性名称
}
}
三、继承
1.多继承
//错误的写法
public class A : B,C
{
}
//正确的写法
public class B : C
{
}
public class A : B //A可访问B,C所有public字段和方法
{
}
2.重写父类和增加子类方法
//【前提】假如Parent,Child类都有共同方法Display,Child类有新增方法Show
Parent parent = new Parent();
Child child = new Child();
Parent parentReferenceToChild = new Child();
parent.Display(); // 调用父类方法
child.Display(); // 调用子类方法
child.Show(); // 调用子类方法
parentReferenceToChild.Display();//调用子类方法,因为父类指向了子类(引用调用,以new为准)
//parentReferenceToChild.Show(); //报错,引用调用时,不允许调用非共有方法
四、多态
常见的实现多态的方式:
- 同一方法,不同的类调用有不同的效果(接口实现或继承重写)
- 同一方法,不同的入参个数,入参类型有不同的效果(方法重载)