سؤال

Consider the code and output:

    using Microsoft.Xna.Framework;
    //Where color is from ^ that
    static Color color = new Color(0, 0, 0, 0);
    static void Main(string[] args)
    {
        Color otherColor = color;
        color.B = 100;

        Console.WriteLine(otherColor.B);
        Console.WriteLine(color.B);

        Console.ReadLine();
    }
    //output
    //0   <-- otherColor
    //100 <-- color

However, I would like otherColor to carry the same value by reference, such that the output would become

//100
//100

If possible, how could I achieve this?

هل كانت مفيدة؟

المحلول

You cannot do what you want to do, at least, not directly.

The Color type is a struct. It's a value type. Each instance of Color is a separate copy of the value. It is not possible to get two Color instances to refer to the same object, any more than it is possible for two int instances to refer to the same object.

Now, you might be able to hack something by including the Color within your own class. The following has not been tested:

public class ColorByReference
{
    Color TheColor {get;set;}
}

static ColorByReference color = new ColorByReference {Color = new Color(0,0,0,0)};
static void Main(string[] args)
{
    ColorByReference otherColor = color;
    color.TheColor.B = 100;

    Console.WriteLine(otherColor.TheColor.B);
    Console.WriteLine(color.TheColor.B);

    Console.ReadLine();
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top