overloading explicit CAST operator with user-defined interface parameter

我的未来我决定 提交于 2019-12-11 02:19:13

问题


At these given classes

[ActiveRecord]
public class BaseMoo : ActiveRecordBase

[ActiveRecord]
public class Foo : BaseMoo { }

somewhere in the code i do

var fooObj = new Foo();
// do something with fooObj
BaseMoo obj = fooObj;

here i try to cast

var newFooObj = (Foo)obj; // and goes well

if i changes the classes to this:

[ActiveRecord(Lazy=true)]
public class BaseMoo : ActiveRecordBase

[ActiveRecord(Lazy=true)]
public class Foo : BaseMoo { }

making it Lazyest at these lines:

var fooObj = new Foo();
// do something with fooObj
BaseMoo obj = fooObj;

the AR creates non a Foo instance instead a BaseMooProxy object

var newFooObj = (Foo)obj; // this throws an invalidcast exception

As sugested by @Adam Houldsworth in this question

I overloads the Foo explicit operator in this way

public static explicit operator Foo(NHibernate.Proxy.INHibernateProxy nhProxy)
{
    var resultObj = (Foo)nhProxy.InSomeWayIGetTheOriginalObject(); // InSomeWayIGetTheOriginalObject() is not a real method, only for simplify
    return resultObj;
}

but i get an error in the operator overload parameter

NHibernate.Proxy.INHibernateProxy nhProxy

user-defined conversion from interface

QUESTION:

  1. how can i do to explicit convert from BaseMooProxy (NHibernate.Proxy.INHibernateProxy) to Foo?

  2. As know it's not possible to overloads the "is" operator, is there a way to do work the "obj is Foo" ?

As the consumer application is 3th part customer It's not possible to changes the way how the application casts the classes objects.

thanks in advance.

来源:https://stackoverflow.com/questions/8833227/overloading-explicit-cast-operator-with-user-defined-interface-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!