可以在VB.NET中追溯实现接口吗?

编程入门 行业动态 更新时间:2024-10-28 14:36:13
本文介绍了可以在VB.NET中追溯实现接口吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

是否可以定义一个接口(例如MyClass实现MyInterface),其方法/属性定义已与第三方(或本机)类上定义的某些方法/属性匹配?

Is it possible to define an interface (e.g. MyClass Implements MyInterface) whose method/property definitions already match some of the methods/properties defined on a third-party (or a native) class?

例如,DataRow类具有许多使其类似于行"的属性/方法.如果我要实现一个接口(即IRowLike),该接口定义本机DataRow类(我无法直接接触或扩展)上已经存在的某些方法和属性,该怎么办?我只是希望该类在运行时同意确实遵守某些接口.

For example, the DataRow class has a number of properties/methods that make it "row-like". What if I want to implement an interface (i.e. IRowLike) that defines certain methods and properties already existing on the native DataRow class (which I cannot directly touch or extend). I simply want the class to agree at runtime that it does indeed abide by some interface.

接口提供了穷人版的鸭子打字".一旦有了一组所有都遵守给定接口的类,就可以针对该接口定义扩展方法,并且所有支持该接口的类都会立即获得新的行为.我知道想对第三方类追溯应用接口似乎很奇怪,但这绝对可以使我们用更少的代码做更多的事情.

Interfaces afford a poor-man's version of "duck typing". Once I have a set of classes that all abide by a given interface, I can define extension methods against that interface and all classes that support the interface immediately gain new behavior. I know it may seem odd to want to retroactively apply an interface against third-party classes, but it would definitely allows us to do more with less code.

推荐答案

.Net中无法实现.类型定义了在编译时在元数据中实现的接口,并且其定义在运行时不可更改.可以在运行时生成实现特定接口但不更改现有类型

This isn't possible in .Net. A type defines the interfaces that it implements in metadata at compile time and its definition isn't alterable at runtime. It is possible to generate types at runtime which implement specific interfaces but not alter an existing type

尽管有一些替代方法.在VB.Net中,您可以简单地选择对类型使用后期绑定并以这种方式(或C#中的dynamic)访问接口方法.缺点当然是代码不是静态可验证的.

There are some alternatives though. In VB.Net you could simply choose to use late binding on the type and access the interface methods in that manner (or dynamic in C#) The downside of course is the code isn't statically verifiable.

更多推荐

可以在VB.NET中追溯实现接口吗?

本文发布于:2023-11-16 13:33:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1604747.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:接口   VB   NET

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!