可以在VB.NET中追溯实现接口吗? [英] Can an interface be retroactively implemented in VB.NET?

查看:88
本文介绍了可以在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中追溯实现接口吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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