笔记:显示实现接口如何实现,作用是什么
一、目的:简要介绍显示实现接口的如何实现,作用是什么
显式实现接口是指在类中实现接口的方法或属性时,必须在方法或属性的声明中显式地指定接口名称。显式实现的接口成员只能通过接口引用访问,而不能通过类的实例直接访问。
二、实现
1. 定义接口
首先,定义一个接口,其中包含一些方法或属性。
public interface IExample
{void DoSomething();string GetInfo();
}
2. 显式实现接口
在类中实现接口的方法和属性时,必须在方法或属性的声明中显式地指定接口名称。
public class ExampleClass : IExample
{void IExample.DoSomething(){Console.WriteLine("Doing something...");}string IExample.GetInfo(){return "Example information";}
}
使用示例
class Program
{static void Main(string[] args){IExample example = new ExampleClass();example.DoSomething(); // 通过接口引用访问方法Console.WriteLine(example.GetInfo());}
}
在这个示例中,ExampleClass 显式实现了 IExample 接口的方法和属性。要调用这些方法和属性,必须将 ExampleClass 的实例转换为 IExample 接口类型。
三、作用
1. 避免命名冲突
显式实现接口可以避免命名冲突。如果类实现了多个接口,并且这些接口中有同名的方法或属性,显式实现可以确保每个接口的方法或属性都能正确实现。
示例:
public interface IFirst
{void DoSomething();
}public interface ISecond
{void DoSomething();
}public class ExampleClass : IFirst, ISecond
{void IFirst.DoSomething(){Console.WriteLine("First interface implementation");}void ISecond.DoSomething(){Console.WriteLine("Second interface implementation");}
}class Program
{static void Main(string[] args){IFirst first = new ExampleClass();ISecond second = new ExampleClass();first.DoSomething(); // 输出: First interface implementationsecond.DoSomething(); // 输出: Second interface implementation}
}
2. 控制接口成员的可见性
显式实现的接口成员只能通过接口引用访问,而不能通过类的实例直接访问。这可以提高封装性,防止接口成员被意外调用。
示例:
public interface IExample
{void DoSomething();
}public class ExampleClass : IExample
{void IExample.DoSomething(){Console.WriteLine("Doing something...");}public void AnotherMethod(){Console.WriteLine("Another method");}
}class Program
{static void Main(string[] args){ExampleClass example = new ExampleClass();// example.DoSomething(); // 编译错误: 'ExampleClass' does not contain a definition for 'DoSomething'example.AnotherMethod(); // 输出: Another methodIExample iExample = example;iExample.DoSomething(); // 输出: Doing something...}
}
总结
显式实现接口用于避免命名冲突和控制接口成员的可见性。显式实现的接口成员只能通过接口引用访问,而不能通过类的实例直接访问。这种实现方式在处理多个接口的同名成员或希望提高封装性时非常有用。
需要了解的知识点
显式接口实现 - C# | Microsoft Learn
如何显式实现接口成员 - C# | Microsoft Learn
如何显式实现两个接口的成员 - C# | Microsoft Learn
了解更多
System.Windows.Controls 命名空间 | Microsoft Learn
控件库 - WPF .NET Framework | Microsoft Learn
WPF 介绍 | Microsoft Learn
XAML概述 - WPF .NET | Microsoft Learn
Windows Presentation Foundation 简介 - WPF .NET | Microsoft Learn
使用 Visual Studio 创建新应用教程 - WPF .NET | Microsoft Learn
适用于 .NET 8 的 WPF 的新增功能 - WPF .NET | Microsoft Learn
适用于 .NET 7 的 WPF 的新增功能 - WPF .NET | Microsoft Learn
System.Windows.Controls 命名空间 | Microsoft Learn
Reference Source
Sysinternals - Sysinternals | Microsoft Learn
Windows app development documentation - Windows apps | Microsoft Learn
欢迎使用 Expression Blend | Microsoft Learn
https://learn.microsoft.com/zh-cn/dotnet/desktop/wpf/?view=netdesktop-7.0&WT.mc_id=MVP_380318
https://github.com/HeBianGu
HeBianGu的个人空间-HeBianGu个人主页-哔哩哔哩视频