c# 接口interface基础入门小例子
- 作者: 陆边123
- 来源: 51数据库
- 2021-08-21
复制代码 代码如下:
/// <summary>
/// interface
/// 与抽象类的区别:
/// 1,abstract可以有具体方法和抽象方法(必须有一个抽象方法),interface没有方法实现
/// 2,abstract可以有构造函数和析构函数,接口不行
/// 3,一个类可以实现多个interface,但只能继承一个abstract
/// 特点:
/// interface成员隐式具有public,所以不加修饰符
/// 不可以直接创建接口的实例,如:iperson xx=new iperson()//error
/// </summary>
public interface iperson
{
string name { get; set; }//特性
datetime brith { get; set; }
int age();//函数方法
}
interface iadderss
{
uint zip { get; set; }
string state();
}
复制代码 代码如下:
/// <summary>
/// interface实现interface
/// </summary>
interface imanager:iperson
{
string dept { get; set; }
}
/// <summary>
/// 实现多个interface
/// 实现哪个interface必须写全实现的所有成员!
/// </summary>
public class employee:iperson,iadderss
{
public string name { get; set; }
public datetime brith { get; set; }
public int age()
{
return 10;
throw new notimplementedexception();
}
public uint zip { get; set; }
public string state()
{
return "alive";
}
}
复制代码 代码如下:
/// <summary>
/// 重写接口实现:
/// 如下,类 employer 实现了iperson,其中方法 age() 标记为virtual,所以继承于 employer 的类可以重写 age()
///
/// </summary>
public class employer:iperson
{
public string name { get; set; }
public datetime brith { get; set; }
public virtual int age()
{
return 10;
}
}
public class work:employer
{
public override int age()
{
return base.age()+100;//其中base是父类
}
}
实现,对象与实例:
复制代码 代码如下:
#region #interface
employee eaji = new employee()
{
name = "aji",
brith = new datetime(1991,06,26),
};
#endregion
#region #interface 的强制转换
iperson ip = (iperson)eaji; //可以通过一个实例来强制转换一个接口的实例,进而访问其成员,
ip.age();
datetime x=ip.brith;
//也可以写成这样:
iperson ip2 = (iperson) new employee();
//但是这样子有时候不是很安全,我们一般用is 和 as来强制转换:
if (eaji is iperson)
{
iperson ip3 = (iperson)eaji;
}
//但is并不是很高效,最好就是用as:
iperson ip4 = eaji as iperson;
if (ip4 != null)//用as时,如果发现实现ip4的类没有继承 iperson,就会返回null
{
console.writeline(ip4.age());
}
#endregion
推荐阅读
- C#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源
热点文章
团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
0
使用 MSBuild.exe 在发布模式下构建 C# 解决方案
0
当我发布 Web 应用程序时,AfterPublish 脚本不运行
0
构建时 T4 转换的产品仅在下一个构建中使用
0
ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
0
新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
0
如何将条件编译符号(DefineConstants)传递给 msbuild
0
MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
0
NuGet 包还原找不到包,没有源
0
使用 C# 6.0 功能运行 TFS 构建
0
