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; 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? 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. 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:
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>( );
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.