简体   繁体   English

是否可以重载我不拥有的类的隐式或显式强制转换运算符?

[英]Is it possible to overload an implicit or explicit cast operator of a class I don't own?

Pretty much all in the title. 标题中几乎所有内容。 Is it possible to create a cast overload on a class that I don't own. 是否可以在我不拥有的类上创建强制类型转换重载。 For instance, if I were to create a wrapper for the NotifyIcon class (which is sealed), I can't actually use it with anything; 例如,如果我要为NotifyIcon类创建一个包装器(已密封),则实际上不能将其与任何东西一起使用。 I'd have to return an instance which kinda kills the ability to do a decorator. 我必须返回一个实例,该实例会破坏执行装饰器的能力。 Is it possible to create a cast overload somewhere where I can basically return the private instance of NotifyIcon? 是否可以在基本上可以返回NotifyIcon私有实例的地方创建强制转换过载? Sounds wonky, but I think it'll achieve what I want. 听起来很古怪,但我认为它将实现我想要的。

Normally, I'd do something like: 通常,我会做类似的事情:

public static implicit operator MyClass(SomeOtherClass input)
{
    // do things to come up with a MyClass
}

But this only works when the return type is MyClass. 但这仅在返回类型为MyClass时有效。 I'd like to do something simple like: 我想做一些简单的事情:

public class MyPsuedoDecoratorClass
{
    private NotifyIcon _icon;

    public MyPsuedoDecoratorClass(NotifyIcon icon)
    {
        _icon = icon;
    }

    // some decorated methods

    public static implicit operator NotifyIcon(MyPsuedoDecoratorClass input)
    {
        return _icon;
    }   
}

So that I can use it as an initialization wrapper. 这样我就可以将其用作初始化包装器。

You basically can't, but you can use NotifyIcon 's tag to store it's artificial derived object which is still elegant: 您基本上不能,但是可以使用NotifyIcon的标签来存储它的人造派生对象,该对象仍然很优雅:

public static class NotifyIconExtesionMethods {
    public static MyClass As<T>( this NotifyIcon notifyIcon ) {
        return notifyIcon.Tag as T;
    }
}

class MyClass {
    private NotifyIcon notifyIcon;

    public MyClass( ) {
        notifyIcon = ...;
        ...
        notifyIcon.Tag = this;
    }
    public T As<T>( ) {
        return notifyIcon as T;
    }
}

//In some method:
var notifyIcon = new MyClass( ).As<NotifyIcon>( );
...
var myClass = notifyIcon.As<MyClass>( );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM