问题
I have this Class:
namespace JimWcfFormTest3
{
[DataContract]
public class GateInfo
{
[DataMember]
public int carid { get; set; }
[DataMember]
public int paid_at_gate { get; set; }
[DataMember]
public int wash_pkg_purch { get; set; }
[DataMember]
public string carte { get; set; }
public override string ToString()
{
return "Car ID: " + carid + "Paid at Gate: " + paid_at_gate + "Wash Package: " + wash_pkg_purch + "Ala Carte: " + carte;
}
}
}
That is called by this WCF Service:
namespace JimWcfFormTest3
{
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)]
public class Service1 : IService1
{
private List<GateInfo> _gate;
private Service1()
{
_gate = new List<GateInfo>();
}
public void Gate_to_Server(GateInfo gatein)
{
if (gatein != null) _gate.Add(gatein);
}
public List<GateInfo> Server_to_Term()
{
return _gate;
}
}
}
That is called by this Button on this Form:
private Service1Client server = new Service1Client();
private void button1_Click(object sender, EventArgs e)
{
int carnum = 2;
int pay = 1;
int wash = 5;
string txt = "TEST";
var data_out = new GateInfo { carid = carnum, paid_at_gate = pay, wash_pkg_purch = wash, carte = txt };
server.Gate_to_Server(data_out);
dataGridView1.DataSource = server.Server_to_Term();
Is my ToString override in the right place? How do I properly call the ToString override in the Form, so I can put it in a textBox when the button is clicked?
回答1:
Since you are calling this thru a Web Service, the type GateInfo
is getting serialized back to the client application (your Forms app). If the client application does not have the native GateInfo
type, then you will be using the serialized type, which does not include functions.
To have the ToString
override work on the client side, you need that class to be included in your Forms application. I typically do this "type sharing" by putting shared data types / model objects in a separate class library and have both the server and client use this lib to map object types to.
If you use this approach, make sure you tick the option under the WCF Service Properties to Reuse types in referenced assemblies
. This will let the WCF client generator know to map that type correctly.
来源:https://stackoverflow.com/questions/40851716/c-sharp-override-tostring-and-display-in-textbox