简体   繁体   中英

Calling method from a struct

I'm convering hsb colour to rgb because im converting a java program to c#. However, in the struct for HSBColor, I can't seem to call the methods once I have made an object, like below:

HSBColor Struct

public struct HSBColor
        {
    public static Color FromHSB(HSBColor hsbColor)
            {
                float r = hsbColor.b;
                float g = hsbColor.b;
                float b = hsbColor.b;
                if (hsbColor.s != 0)
                {
                    float max = hsbColor.b;
                    float dif = hsbColor.b * hsbColor.s / 255f;
                    float min = hsbColor.b - dif;

                    float h = hsbColor.h * 360f / 255f;

                    if (h < 60f)
                    {
                        r = max;
                        g = h * dif / 60f + min;
                        b = min;
                    }

                }

       ***I know there are missing brackets here, only using snippets of code***

mandelbrot

 private void mandelbrot() // calculate all points
        {
            HSBColor hsbcolor = new HSBColor();
            hsbcolor.FromHSB(h, 0.8f, b);
        }

the "FromHSB" in the hsbcolor.FromHSB(h, 0.8f, b) ; line is underlined stating the error:

Error 3 'Fractal.Form1.HSBColor' does not contain a definition for 'hsbColor' and no extension method 'hsbColor' accepting a first argument of type 'Fractal_Assignment.Form1.HSBColor' could be found (are you missing a using directive or an assembly reference?)

public static Color FromHSB(HSBColor hsbColor)

This means it's a static function. You access a static function by class name.

hsbcolor.FromHSB(h, 0.8f, b);

hsbcolor is a variable here. Change this line into

Color color = HSBColor.FromHSB(h, 0.8f, b);

According to your method signature

  public static Color FromHSB(HSBColor hsbColor)

you have to put something like this:

  // "static" wants class (i.e. HSBColor) not instance
  // FromHSB wants one HSBColor argument: "new HSBColor(...)"
  Color result = HSBColor.FromHSB(new HSBColor(h, 0.8f, b));

a better implementation is to convert FromHSB from static into instance method:

  public struct HSBColor {
    // note no "static" here
    public Color ToColor() {
      float r = this.b; // change "hsbColor" into "this "
      float g = this.g; 
      ...
    }

so you can put it

  Color result = (new HSBColor(h, 0.8f, b)).ToColor();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM