问题
This is my service generated class:
public partial class MyClass : object,
System.Runtime.Serialization.IExtensibleDataObject,
System.ComponentModel.INotifyPropertyChanged
{ }
I'm using my own service. In MyClass
I have overridden ToString()
but I don't have it in my client. I want either to generate it or as MyClass
is partial am I able to override ToString
myself?
I know that I can write in generated .cs file. What is the best way to do it and at all should I do it?
回答1:
If you are defining both the client and the service, you don't need to use the WSDL-generate classes. Move the shared objects into a separate assembly, and reference it from both client and server projects. When you create the service reference, there's an "advanced" option (which I think is on by default) that reuses any known classes from the WSDL instead of generating new ones.
Even better, if you move the service contract into your shared library, you don't even need to create the service reference, you can just call the ChannelFactory
directly and eliminate the entire auto-generated proxy class.
I have a demonstration on how to do both of these things on my blog: http://blog.kutulu.org/2012/03/proxy-free-wcf-ditching-proxy.html
If you absolutely need to use the WSDL from the service (e.g. you don't have control over the service side and it could change on you), then you can extend the partial classes that VS creates (as you suggested). Most auto-generate classes you get from VS these days are partial classes specifically to make this kind of extension possible. The downside, of course, is that nothing guarantees client and server's additional partial class methods are the same. I'd definitely consider this a last-resort option.
回答2:
If you share the dll where overriden method exixts between client and server project, you can use the method. By default, WCF generates each class with only properties declared in the service interface. No method is generated.
You can just create a seperate dll file and put what you want to share between service and client into this dll; and add this dll as a reference to both client and service projects. By default, when you generate the proxy, it will not auto generate the shared classes.
来源:https://stackoverflow.com/questions/10850111/override-tostring-method-in-wcf-service