Is it possible to create a reference loop using only value types?

As an explanation, take this type of value in C #:

struct ObjRef
{
    public object Value;
    public ObjRef(object value) { Value = value; }
}

I can imagine a graph of objects where there are two instances in a box of this type, each of which contains a link to the other. This is what I mean by a reference loop with value types only.

My question is whether it is ever possible to build such a graph of objects in .NET. In theory, the design, if it exists, will look like this:

object left = new ObjRef();
object right = new ObjRef(left);
left.Value = right;

but obviously the last line is invalid C #. Create the last line:

((ObjRef)left).Value = right;

does not achieve the result, as the casts are unpacked left, and you end up mutating the copy. So, at least in direct C #, this is not like a construct.

- , , , dynamic, IL - ? - , CLR ?

, . , , , / .


, , , . :

interface IObjRef
{
    IObjRef Value { get; set; }
}

struct ObjRef : IObjRef
{
    IObjRef value;
    public IObjRef Value { get { return value; } set { this.value = value; } }
    public ObjRef(IObjRef value) { this.value = value; }
}

:

IObjRef left = new ObjRef();
IObjRef right = new ObjRef(left);
left.Value = right;

โ„– 72, .

+5
3

, . , , , .

interface ICycle
{
    void SetOther(ICycle other);
}

struct Cycle : ICycle
{
    ICycle value;
    public void SetOther(ICycle other)
    {
        value = other;
    }
}

class Example
{
    static void CreateCycle()
    {
        ICycle left = new Cycle();   // Left is now boxed
        ICycle right = new Cycle();  // Right is now boxed
        left.SetOther(right);
        right.SetOther(left);  // Cycle
    }
}

, , .

+2

, , , Value , boxed, .

, , , . , ?

+1

I did not know that structures can implement interfaces. It seems really freaky; what is it useful for? Is hostility to structures in general or to structures with properties and methods that act on them? This is too bad .net does not allow you to declare certain structure properties and methods as mutators, the use of which in ReadOnly structures would be prohibited.

0
source

All Articles