开发者

beginner's c# class question

开发者 https://www.devze.com 2023-01-20 10:29 出处:网络
public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void txtTestPrime_Click(object sender, EventArgs e)
public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void txtTestPrime_Click(object sender, EventArgs e)
        {
            TestPrime myNumber = new TestPrime();
            lblAnswer.Text = 
                myNumber.TestPrime(ToInt16(txtTestPrime.Text)) ? "it is prime!" : "it is NOT prime!";
        }

    }
    public class TestPrime(int number)
    {
        bool prime;


    }

it doesnt like this line:

public class TestPrime(int number)

i am getting this error: invalid token '(' in class, struct, or interface member declaration

also getting expect { and ; on that line

also on this line:

myNumbe开发者_运维技巧r.TestPrime(ToInt16(txtTestPrime.Text)) ? "it is prime!" : "it is NOT prime!"; 

im getting Error 4 'WindowsFormsApplication1.TestPrime' does not contain a definition for 'TestPrime' and no extension method 'TestPrime' accepting a first argument of type 'WindowsFormsApplication1.TestPrime' could be found (are you missing a using directive or an assembly reference?)

perhaps it is one main thing that i am doing wrong. please help!


Is TestPrime supposed to be a class? It sounds more like a function (also called "method").

Try changing that line to

public static bool TestPrime(int number)


You are trying to create a class and a method on the same line at the same time, that just don't make any sense.

If you want a method to check the number, do the following:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void txtTestPrime_Click(object sender, EventArgs e)
    {
        // this instantiate a new class, which now is not needed
        //TestPrime myNumber = new TestPrime();
        lblAnswer.Text = TestPrime(Int16.Parse(txtTestPrime.Text)) ? "it is prime!" : "it is NOT prime!";
    }

    public bool TestPrime(short number)
    {
        /* your logic */
        /* this method expects a boolean as the return type */
    }
}

Some useful links:

  • Introduction to C# Classes
  • C# Methods


You can't have parameters in a class declaration.

You need to create a constructor taking the desired parameters.

Example:

public class TestPrime
{
        private bool prime;
        private int _number;
        public TestPrime(int number) 
        {
           this._number = number;
        }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消