lundi 15 avril 2019

Deferred initialization "proxy" in C#

Suppose I have an object tree, with objects from a (quite large) set of classes; classes more or less under my control (and say, each implementing IBaseInterface, for semantic typing). The tree is normally filled in a depth-first manner. At times, however, the nodes must be created at a different location in the execution flow; hence I need something that can act as a placeholder (proxy-like) for the objects. The placeholder should hold a reference to where it was created, without any other interference with the underlying type/object (decorator-style).

I was thinking of something similar to

interface IPlaceholder
{
    PositionReference RealLocation { get; }
}

class Placeholder<T> : T, IPlaceholder
{
    PositionReference RealLocation { get; private set; }
}

However, this wouldn't work since C# cannot have generic classes inheriting from their type parameters.

A brute-force approach would be, of course, to dynamically generate classes at runtime to specification; but this seems a bit too extreme (and cumbersome, if I have to fiddle with Reflection.Emit manually).

What would be the best approach to create such placeholder objects?

(Extra note: This is pretty much like Lazy<T>, except that the object is normally expected to be of the original type; when not, the proxied object cannot be constructed before the parent node is processed.)

Aucun commentaire:

Enregistrer un commentaire