开发者

c# Is it possible to use Extensions Methods to implement Implicit conversions? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

C#: implicit operator and extension methods

I have a common library project defining a number of types (nothing too complex, just properties mainly). Two projects are referencing this common library: a client application and a webservice.

My intention is for the webservice to return type T, then use T in the client application. Normally I'd have to convert the type returned by the webservice to T again (because of the proxy class, T is returned as WebService.T), but I'm hoping to use implicit conversion instead.

As the original Common class has no knowledge of the web service proxy class, I'm wondering if I could make use of extension methods to implement the implicit conversion. Sort of something like

public static implicit operat开发者_StackOverflow中文版or MyObject(this MyProxyObject value)
    {
        //stuff
    }

which the compiler doesn't like at all.

Is something like this even possible?

Update

Ok, first off I had the 2.0 framework referenced so that explains my compiler problems.

Secondly, I'm able to achieve the conversion by creating a method extension "ToModel" (or something). So in terms of the business objective, I will be able to easily convert my types by calling WebService.T.ToModel().

Though I doubt this could be done using implicit conversion (or whether its worth the trouble).


If your web service is a WCF service and not a legacy ASMX service, then you could configure the service reference on the client side to ‘reuse types in referenced assemblies’. This will result in the client-side using the types in your common library instead of auto-generating proxy classes on the client-side.


There's no need for that with extension methods. You should be able to remove this and it should compile. Or it might make more sense to have it as an explicit cast.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜