We have the following..
public class Foo
{
public string Name { get; private set;}
private Foo(string name)
{
Name = name;
}
public Foo Instance1 = new Foo("Hello");
public Foo Instance2 = new Foo("World");
}
And then referencing this we would have..
[ProtoContract]
public class Bar
{
[ProtoMember(1)]
public Foo Foo { get; private set; }
public Bar(Foo foo)
{
Foo = foo;
}
}
So when I deserialize a Bar I need it to get a reference to either Foo.Instance1 or Foo.Instance2..
The question is can I do this and if so how?
There are several ways this could be approached. The simplest would be to add a shim property, i.e.
However, if you have lots of
Fooproperties this could be a pain. So instead, v2 offers “surrogate” types – i.e. as long as it can locate a conversion operator between 2 types, it will happily swap them for you automatically. In this case we’d want to swap to an enum, and since you can’t add operators to enums you’d have to add the operator toFoo:and have a simple enum somewhere:
And configure it (somewhere at app-startup):
And we’re good to go. A minor tweak is also required because
Barlacks a parameterless constructor; 2 options here:private Bar() {}that it can use[ProtoContract(SkipConstructor = true)]Add a test rig:
I could probably also make it possible to use external operator-esque methods to avoid having to have the operator on
Foo, which is a bit ugly.A final option would be for me to add
IObjectReferencesupport, but frankly (and especially in this case), using a basic enum for the implementation is tidier and more efficient.