如何编写从接口到另一种类型的隐式转换? [英] How to write Implicit Conversion from an Interface to another type?

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

问题描述

我正在尝试执行以下操作:

I am trying to do something like below:

public class SomeWrapper : ISomeWrapper{

  public static implicit operator ActualRec(ISomeWrapper someWrapper)
        {
            return ((SomeWrapper)someWrapper).SomeInfo;
        }
}

但是此代码失败,并说:参数或返回类型必须为SomeWrapper类型."

But this code fails, saying: "Either parameter or return type must be of type SomeWrapper".

我了解编译说明的问题.但是我需要这种类型的转换b,因为在我的整个应用程序中,我都使用ISomeWrapper作为变量,存储SomeWrapper实例.(此外,SomeWrapper是唯一实现ISomeWrapper的类.)

I Understand the problem that compiling is stating. But I need this type conversionb because throughout my application I am using ISomeWrapper as the variable, storing SomeWrapper instance. (Also, SomeWrapper is the only class implementing ISomeWrapper).

如果ISomeWrapper接口连接到我在具体类中知道的类型,是否有任何方法可以进行隐式转换?

Is there any way to do the implicit conversion if ISomeWrapper interface to the type that i know in my concrete class?

正如所有人所建议的那样,在C#中无法从接口进行隐式强制转换.

As suggested by all, implicit casting from interface is not possible in C#.

我需要这样做的原因?我想允许(隐式)允许ISomeWrapper的用户调用需要ActualRec作为参数的方法,而无需允许ISomeWrapper的用户调用ActualRec的方法/属性.

The reason I need to do this? I want to allow (implicitly) to the user of ISomeWrapper to invoke methods that need ActualRec as the parameter WITHOUT giving access to the users of ISomeWrapper to call methods/properties of ActualRec.

例如,如果我在ISomeWrapper中包含了ActualRec属性,则ISomeWrapper的用户将可以调用ActualRec中可用的方法(例如,someWrapper.ActualRec.Dispose()),我不想公开该方法.

For instance, If I include a property ActualRec in ISomeWrapper then users of ISomeWrapper would be able to call methods available in ActualRec ( Say, someWrapper.ActualRec.Dispose() ), which I DO NOT want to expose.

这就是尝试查找隐式转换的原因.

That's the reason for trying to find some implicit conversion.

此外,我不想在整个应用程序中使用SomeWrapper.

Also, I do not want to user SomeWrapper across application.

请提出是否有一些概念/模式来完成此操作.

Please suggest if there is some concept/pattern to get this done.

感谢您的关注.

推荐答案

我会说您的设计存在缺陷.您正在从接口强制转换为具体类型,这使该接口的使用变得毫无意义.该接口是一个合同,通过该合同,实现类型将符合提供所需的服务集的要求.在您的示例中,接口(合同)中是否未定义 SomeInfo 属性?如果没有,您为什么要尝试使用该接口进行投射?您应该使用 SomeWrapper 作为输入参数本身.

I would say there is a flaw in your design. You're casting to a concrete type from an interface, that makes the use of the interface pretty pointless. The interface is a contract through which implementing types will conform to provide a required set of services. In your example, is the SomeInfo property not defined in the interface (contract)? If not, why are you trying to cast using the interface at all? You should be using SomeWrapper as the input argument itself.

这篇关于如何编写从接口到另一种类型的隐式转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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