
正文
abstract、virtual、sealed、 interface、struct 基础知识整理
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
abstract
|
abstract 修饰符指示被修改内容的实现已丢失或不完整。 abstract 修饰符可用于类、方法、属性、索引和事件。 在类声明中使用 abstract修饰符以指示某个类仅旨在作为其他类的基类。 标记为 abstract 的成员,或包含在抽象类中的成员,都必须由派生自抽象类的类来实现。 |
public abstract class Animal
{
public abstract void Breath();
} // Error 不能创建实例
Animal animal = new Animal(); public class Dog : Animal
{
public override void Breath()
{
System.Console.WriteLine("呼呼呼");
}
}
1.被
abstract
修饰的Animal类是不完整的,所以不能创建实例,只能被继承。
2.被
abstract
修饰的Breath方法内容已丢失,所以并没有方法主体,必须在基类中重写。
virtual
| virtual关键字用于修改方法、属性、索引器或事件声明,并使它们可以在派生类中被重写。 |
public abstract class Animal
{
public virtual void Breath()
{
System.Console.WriteLine("深呼吸~");
}
}
public class Dog : Animal
{
public override void Breath()
{
System.Console.WriteLine("旺旺旺");
}
} Dog dog = new Dog();
dog.Breath();
1.被
virtual
修饰的Breath方法,必须有方法体。在基类中可以重写,也可以不重写。
interface
|
接口只包含方法、属性、事件或索引器的签名。 实现接口的类或结构必须实现接口定义中指定的接口成员。 |
public interface ISampleInterface
{
void SampleMethod();
} public class ImplementationClass : ISampleInterface
{
public void SampleMethod()
{
//
}
}
1.
interface
中的方法不能包含方法体。
2.在基类中必须实现接口定义的成员。
sealed
|
应用于某个类时,sealed修饰符可阻止其他类继承自该类。 应用于方法或属性时,sealed修饰符必须始终与 override 结合使用。 |
public sealed class Dog : Animal
{
public override void Breath()
{
System.Console.WriteLine("旺旺旺");
}
} public class Dog1 : Dog
{
// cannot inherit from sealed class 'Dog'
}
public class Animal
{
public virtual void Breath()
{
}
}
public class Dog : Animal
{
public sealed override void Breath()
{
System.Console.WriteLine("旺旺旺");
}
} public class BigDog : Dog
{
public override void Breath()
{
// Error : Dog.Breath() 是密封的,无法重写
}
}
struct
|
struct 是一种值类型,通常用来封装小型相关变量组。 struct 也可以实现接口,且实现方法与类相同。 struct 可以包含构造函数、常量、字段、方法、属性、索引器、运算符、事件和嵌套类型,但如果同时需要上述几种成员,则应当考虑改为使用类作为类型。 |
public struct Book
{
public decimal price;
public string title;
public string author; // 构造函数必须有参数,在构造函数中必须给所有成员赋值。
public Book(decimal price,string title , string author)
{
this.price = price;
this.title = title;
this.author = author;
}
} var b = new Book(100M,"和谐","布吉岛");
参考文档:
https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/keywords/
https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/keywords/
| 本文博客园地址:http://www.cnblogs.com/struggle999/p/7055787.html |
如果您觉得阅读本文对您有帮助,请点一下“推荐”按钮,您的“推荐”将是我最大的写作动力!欢迎各位转载,但是未经作者本人同意,转载文章之后必须在文章页面明显位置给出作者和原文连接,否则保留追究法律责任的权利。








