Cześć.
Mam mały problem.
Mam strukturę RGB, gdzie przechowuję jak się domyślacie, wartości składowych RGB.
struct RGB
{
private const int MIN_RGB_VALUE = 0;
private const int MAX_RGB_VALUE = 255;
public int A;
public int R;
public int G;
public int B;
public RGB(int r, int g, int b)
{
this.A = MAX_RGB_VALUE;
this.R = r;
this.G = g;
this.B = b;
}
}
I działa ok, jednak konstruktorów w tej strukturze mam więcej. Np z parametrami (int a, int r, int g, int b), (int r, int g, int b) oraz (RGB rgb).
I teraz w każdej strukturze muszę robić tak:
public RGB(int r, int g, int b)
{
this.A = MAX_RGB_VALUE;
this.R = r;
this.G = g;
this.B = b;
}
public RGB(int a, int r, int g, int b)
{
this.A = a;
this.R = r;
this.G = g;
this.B = b;
}
public RGB(RGB rgb)
{
this.A = rgb.A;
this.R = rgb.R;
this.G = rgb.G;
this.B = rgb.B;
}
Co powoduje, że powielam cały czas jeden i ten sam kod - przypisywania.
Toteż napisałem funkcję:
public void SetRGB(int r, int g, int b)
{
R = r;
G = g;
B = b;
}
public void SetARGB(int a, int r, int g, int b)
{
SetRGB(r, g, b);
this.SetAValue(a);
}
Ale, gdy dodaję ją w konstruktorze to wywala mi błąd:
public RGB(int r, int g, int b)
{
this.SetARGB(MAX_RGB_VALUE, r, g, b);
}
The 'this' object cannot be used before all of its fields are assigned to
Field 'Program.RGB.A' must be fully assigned before control leaves the constructor
Field 'Program.RGB.R' must be fully assigned before control leaves the constructor
Field 'Program.RGB.G' must be fully assigned before control leaves the constructor
Field 'Program.RGB.B' must be fully assigned before control leaves the constructor
Moje pytanie brzmi:
Czy można w konstruktorze struktury wywołać funkcję przypisania bez wcześniejszego powielania tego kodu?
Chciałbym po prostu stworzyć takie konstruktory:
public RGB(int r, int g, int b)
{
this.SetARGB(MAX_RGB_VALUE, r, g, b);
}
public RGB(int a, int r, int g, int b)
{
this.SetARGB(a, r, g, b);
}
public RGB(RGB rgb)
{
this.SetARGB(rgb.A, rgb.R, rgb.G, rgb.B);
}
Niestety wywołuje to błędy. Jeśli w taki sposób nie jest to możliwe to dlaczego?
Dlaczego w strukturze nie jest to możliwe, a w klasie tak?
Z góry dziękuję za odpowiedź.