C#接口的实现和类型断言
·
C#接口的实现和类型断言
在C#中,接口定义了一组契约,实现类必须遵循这些契约提供具体实现。类型断言则用于运行时类型检查和转换,主要通过is和as运算符实现。
1. 接口实现
接口通过interface关键字定义,实现类使用:符号声明:
// 定义接口
public interface IShape
{
double CalculateArea(); // 方法签名
string Name { get; } // 属性签名
}
// 实现接口
public class Circle : IShape
{
public double Radius { get; set; }
public double CalculateArea() => Math.PI * Radius * Radius; // 实现方法
public string Name => Circle // 实现属性
}
关键点:
- 实现类必须提供接口所有成员的具体实现
- 类可实现多个接口(如
class MyClass : IInterface1, IInterface2) - 显式实现可解决命名冲突:
double IShape.CalculateArea() { ... }
2. 类型断言
用于安全地检查和转换对象类型:
is运算符:检查类型兼容性,返回布尔值object obj = new Circle(); if (obj is IShape shape) { Console.WriteLine(shape.Name); // 安全访问 }as运算符:尝试转换类型,失败返回nullIShape shape = obj as IShape; if (shape != null) { Console.WriteLine(shape.CalculateArea()); }
对比:
| 运算符 | 失败返回值 | 适用场景 |
|---|---|---|
is | false | 条件判断 类型转换 |
as | null | 直接转换,避免异常抛出 |
3. 完整示例
using System;
// 接口定义
public interface ILoggable
{
void Log(string message);
}
// 实现类
public class FileLogger : ILoggable
{
public void Log(string message) => Console.WriteLine($: {message}\n
public class DatabaseLogger : ILoggable
{
public void Log(string message) => Console.WriteLine($: {message}\n
class Program
{
static void Main()
{
object logger = new DatabaseLogger();
// 类型断言使用
if (logger is ILoggable loggable)
{
loggable.Log( started // 输出: Database: Operation started
}
// 安全转换
ILoggable fileLogger = new FileLogger() as ILoggable;
fileLogger?.Log(up complete 输出: File: Backup complete
}
}
最佳实践:
- 优先使用
is进行类型检查和转换(C# 7.0 模式匹配) - 接口实现应遵循里氏替换原则(LSP)
- 避免直接强制转换(
(Type)obj),可能引发InvalidCastException
通过接口实现多态性,结合类型断言可编写灵活且类型安全的代码。
更多推荐



所有评论(0)