gpt4 book ai didi

c# - 如何编写从接口(interface)到另一种类型的隐式转换?

转载 作者:行者123 更新时间:2023-11-30 13:20:40 24 4
gpt4 key购买 nike

我正在尝试做如下的事情:

public class SomeWrapper : ISomeWrapper{

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

但是这段代码失败了,说:“参数或返回类型必须是 SomeWrapper 类型”。

我理解编译所陈述的问题。但我需要这种类型转换,因为在我的整个应用程序中,我都使用 ISomeWrapper 作为变量,存储 SomeWrapper 实例。 (另外,SomeWrapper 是唯一实现 ISomeWrapper 的类)。

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

编辑:正如所有人所建议的那样,在 C# 中不可能从接口(interface)进行隐式转换。

我需要这样做的原因是什么?我想(隐含地)允许 ISomeWrapper 的用户调用需要 ActualRec 作为参数的方法,而不允许 ISomeWrapper 的用户调用 ActualRec 的方法/属性。

例如,如果我在 ISomeWrapper 中包含属性 ActualRec,那么 ISomeWrapper 的用户将能够调用 ActualRec 中可用的方法(比如说,someWrapper.ActualRec.Dispose()),我不想公开这些方法。

这就是试图找到一些隐式转换的原因。

此外,我不想跨应用程序使用 SomeWrapper。

如果有一些概念/模式可以完成这项工作,请提出建议。

感谢您的关注。

最佳答案

这在 C# 中是受限的。阅读下文。

http://msdn.microsoft.com/en-us/library/aa664464%28VS.71%29.aspx

A class or struct is permitted to declare a conversion from a source type S to a target type T provided all of the following are true:

...

Neither S nor T is object or an interface-type.

此外,

User-defined conversions are not allowed to convert from or to interface-types. In particular, this restriction ensures that no user-defined transformations occur when converting to an interface-type, and that a conversion to an interface-type succeeds only if the object being converted actually implements the specified interface-type.

关于c# - 如何编写从接口(interface)到另一种类型的隐式转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5746161/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com