VB.Net 中的接口行为不同 [英] Interface behavior is dfferent in VB.Net

查看:26
本文介绍了VB.Net 中的接口行为不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

界面在 Vb.Net 中的行为不同.下面是一个示例代码片段,其中 ISudent 接口有一个方法 SayHello,该方法由 Student 类实现.SayHello 的访问修饰符默认应为 Public.通过将访问修饰符更改为 Private 不会破坏现有代码,我仍然可以使用以下代码访问此私有方法

Interface behaves differently in Vb.Net. Below is a sample code snippet where IStudent interface has a method SayHello which is implemented by a class Student. The Access modifier for SayHello should be Public by default. By changing Access modifier to Private is not breaking the existing code and still i can access this private method using below code

Dim stdnt As IStudent = New Student
stdnt.SayHello()

访问修饰符决定了类中成员的范围,更多的私有成员只能从存在的类中访问.但是在这里访问修饰符,封装的理论被打破了.

Access modifier determines the scope of the members in a class, more over private members are accessible only from the class which exists. But here the theory of Access Modifier, Encapsulation are broken.

  • .net 为什么要这样设计?
  • 访问修饰符和封装的概念真的被打破了吗?
  • .net 框架如何在内部处理这种情况?

提前致谢

Module Module1

   Sub Main()
        Dim stdnt As IStudent = New Student
        stdnt.Name = "vimal"
        stdnt.SayHello()
   End Sub

End Module

Public Interface IStudent

   Property Name As String

   Sub SayHello()

End Interface

Public Class Student
   Implements IStudent

   Private Property Name As String Implements IStudent.Name

   Private Sub SayHello() Implements IStudent.SayHello
       Console.WriteLine("Say Hello!")
   End Sub

End Class

推荐答案

原发帖者通过 TheBugGuys@Coverity.com 向我提交了这个问题;我的答案在这里:

The original poster submitted this question to me via TheBugGuys@Coverity.com; my answer is here:

https://communities.coverity.com/blogs/development-testing-blog/2013/10/09/oct-9-posting-interface-behaves-differently-in-visual-basic

简单总结:

为什么.NET 是这样设计的?

Why was .NET designed in this way?

这个问题不可能含糊.

C# 和 VB 中的显式实现是否破坏了封装?

Is encapsulation broken by explicit implementation in C# and VB?

没有.方法的隐私限制了方法的可访问性域name,而不是谁可以调用该方法.如果类的作者选择通过某种机制调用私有方法而不是按名称查找它,那是他们的选择.第三方无法为它们做出选择,除非通过诸如私有反射之类的技术来破坏封装.

No. The privacy of the method restricts the accessibility domain of the methods name, not who can call the method. If the author of the class chooses to make a private method callable by some mechanism other than looking it up by name, that is their choice. A third party cannot make the choice for them except via techniques such as private reflection, which do break encapsulation.

此功能在 .NET 中是如何实现的?

How is this feature implemented in .NET?

有一个用于显式接口实现的特殊元数据表.当 CLR 试图找出哪个类(或结构)方法与哪个接口方法相关联时,首先会参考它.

There is a special metadata table for explicit interface implementations. The CLR consults it first when attempting to figure out which class (or struct) method is associated with which interface method.

这篇关于VB.Net 中的接口行为不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆