Dynamic structures do not work

I have a problem using the class of structures made.

Here's the basic definition:

using System;

struct Real
{
    public double real;

    public Real(double real)
    { 
        this.real = real;
    }
}

class Record
{
    public Real r;
    public Record(double r)
    {
        this.r = new Real(r);
    }
    public void Test(double origval, double newval)
    {
        if (this.r.real == newval)
            Console.WriteLine("r = newval-test passed\n");
        else if (this.r.real == origval)
            Console.WriteLine("r = origval-test failed\n");
        else
            Console.WriteLine("r = neither-test failed\n");
    }
}

When I create a non-dynamic (static?) Record, install Real. When I create a dynamic record, setting up the real one does not work.
When I create a dynamic recording, I replace the real work.

And here is the test program

class Program
{
    static void Main(string[] args)
    {
        double origval = 8.0;
        double newval = 5.0;

        // THIS WORKS - create fixed type Record, print, change value, print
        Record record1 = new Record(origval);
        record1.r.real = newval;        // change value  ***
        record1.Test(origval, newval);

        // THIS DOESN'T WORK.  change value is not making any change!
        dynamic dynrecord2 = new Record(origval);
        dynrecord2.r.real = newval;     // change value
        dynrecord2.Test(origval, newval);

        // THIS WORKS - create dynamic type Record, print, change value, print
        dynamic dynrecord3 = new Record(origval);
        dynamic r = dynrecord3.r;       // copy out value
        r.real = newval;                // change copy
        dynrecord3.r = r;               // copy in modified value
        dynrecord3.Test(origval, newval);

    }
}

And here is the conclusion: r = newval-test passed Error r = origval-test r = newval-test passed

When I change the Real structure to the Real class, all three things work.

So what is going on?
Thanks
Max

+3
source share
3 answers

dynamic - object CLI, . . , . - .

+1

. Mads Torgersen Microsoft.


Mads:

, .

dynrecord2.r.real = newval; // change value

dynrecord2.r , . , , , .

"" #. , , - , :

1) , - , , ,

2) , , - , , ,

# , , , - , .

, , , .


MSIL. , ,

dynrecord2.r.real = newval;

:

Real temp = dynrecord2.r;
temp.real = newval;

dynrecord2.r - , , . dynrecord2.r , , .

, , .

Max

0

Make your structure unchanged and you will have no problems.

struct Real
{
    private double real;
    public double Real{get{return real;}}

    public Real(double real)
    { 
        this.real = real;
    }
}

Interchangeable structures can be useful in native interactions or in some high-performance scenarios, but then you better know what you are doing.

0
source

Source: https://habr.com/ru/post/1775352/


All Articles