Automatic Code Generation-->Implement Interface
https://msdn.microsoft.com/en-us/library/hk90416s(v=vs.110).aspx
VS中自带的只能提示,一个类继承自某一个接口。
由VS为类生成接口所要求的方法
using System; using System.Collections.Generic; using System.Text; using System.ServiceModel; namespace BusinessServiceContracts { [ServiceContract(Namespace = "http://www.thatindigogirl.com/samples/2006/06")] public interface IServiceA { [OperationContract] string Operation1(); [OperationContract] string Operation2(); } }
public class ServiceA : IServiceA, IAdmin { }
现有代码如上
把鼠标的光标点在IServiceA的第一个字母I前面
这个时候会发现I字母线面有一个蓝色的下划线
让鼠标悬停在蓝色的下划线上,会出现一个小图标,单击一下
根据需要选择其中一个,来自动生成代码
实现接口IServiceA
using System; using System.Collections.Generic; using System.Text; using BusinessServiceContracts; namespace BusinessServices { public class ServiceA : IServiceA, IAdmin { public string Operation1() { throw new NotImplementedException(); } public string Operation2() { throw new NotImplementedException(); } } }
显示实现接口IServiceA
using System; using System.Collections.Generic; using System.Text; using BusinessServiceContracts; namespace BusinessServices { public class ServiceA : IServiceA, IAdmin { string IServiceA.Operation1() { throw new NotImplementedException(); } string IServiceA.Operation2() { throw new NotImplementedException(); } } }
第一种,实现接口,是public 方法
第二种,显示实现接口,方法直接完全限定了
显示接口和隐式接口的区别:
https://msdn.microsoft.com/en-us/library/ms173157.aspx
隐式实现的话实现的方法属于实现的类的,可以直接通过类的对象访问,
显式实现的话方法是属于接口的,可以看成是寄托在类中实现的,访问这些方法时要先把对象转换成接口对象,然后通过接口对象调用,
interface ICalculate { void Add(); void Substract(); } class Math : ICalculate { void ICalculate.Add() { throw new NotImplementedException(); } void ICalculate.Substract() { throw new NotImplementedException(); } }
调用方式
Math类型的实例是无法访问Add方法的
只有接口类型的实例,才可以访问Add方法。 即,需要把Math类型的实例先转换ICalculate才会用到
Math math = new Math(); ICalculate iMath = new Math(); iMath.Add();
安装了Resharper之后,上面的功能会被屏蔽
Resharper提示了错误之后,鼠标点击在错误的位置,左侧会出现一个红色灯泡
点击灯泡之后,选择Implementing missing members
作者:Chuck Lu GitHub |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了