Cann't serialize interface

G

Guest

hello

i have one interface and a class inherit the interface like below:
public interface IFoo
{
string FooName
{
get;
set;
}
}

[Serializable()]
public class Foo:IFoo
{
public string FooName
{
get{ ... }
set{ ... }
}
}

And i have one class using Foo like below:
public class FooContainer
{
public IFoo[] Foos { ... }
}

When i create a web service to delive class FooContainer to client, i get an
error means: Can not serialize interface IFoo.

I want to inherit ISerialzable in IFoo like below:
public interface IFoo:ISerializable.
And implement ISerializable in class Foo, but i get the same error.

What should i do to correct it?

thx.
 
R

Robert Jordan

Sahil said:
You can go into the proxy (vb or cs) class generated for the webservice
reference and add the serializable attribute to it. That will make this
work.

It will not work. Fields of interface types are not serializable.
Use this pattern to make them serializable:

[Serializable]
class A {

[NonSerialized]
ISomeInterface Field {
get {
return (ISomeInterface) field;
}
}
private object field;
// or
private ClassImplementingISomeInterface field;

}

bye
Rob
 
R

Robert Jordan

Robert said:
[Serializable]
class A {

[NonSerialized]

Correction: the [NonSerialized] attribute is not necessary (and also
invalid in this context).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top