将接口转换为类 [英] Cast Interface to class

查看:54
本文介绍了将接口转换为类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读OPC客户端代码:

//创建一个组

Opc.Da。 订阅  group;

group =(Opc.Da。
订阅 )server.CreateSubscription(groupState); 

// server.CreateSubscription(groupState)返回接口ISubscription




语法:    group =(Class)Interface

是否意味着将类型转换为类? 

有什么用? 

谢谢

推荐答案

该代码确实将接口强制转换为类。

That code is indeed casting an interface back into a class.

一般来说,这不是一个好主意 - 返回点一个接口允许你编写公共代码,而不需要知道或担心实现它的特定类(甚至可能根据确切的调用或情况而变化)。

Generally, this is not a good idea - the point of returning an interface is that allows you to write common code without needing to know or worry about the specific class that is implementing it (and which may even vary based on the exact call or situation).

但是,如果您知道该接口是由特定类实现的,并且您希望访问该类的其他功能而不是该接口的一部分,那么没有什么能阻止您将其转换为班级。但它确实会导致"bileb"代码变得"脆弱"。不推荐,如果你不需要,恕我直言。

However, if you know that the interface is being implemented by a specific class and you want to access other features of that class that are not a part of the interface then there is nothing stopping you from casting it to the class. But it does tend to lead to 'fragile' code. Not recommended if you don't need to, IMHO.

(注意:我不知道这个代码来自哪里,但请注意,如果你通过'偷看'或其他方式获得它从构建的程序集中反编译,然后你真的在查看反编译器为你重构的代码,这可能实际上并不代表原始代码写的

(NB: I don't know where this code came from, but note that if you acquired it by 'peeking' or otherwise decompiling from a built assembly, then you are really looking at code that the decompiler has reconstructed for you, which may not actually represent the original code-as-written).


这篇关于将接口转换为类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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