简体   繁体   中英

C# Possible method to call protected non-static methods in current class?

I've recently picked up C# as another language to further my knowledge into other languages, but as experimenting to get used to the syntax of the language, I encountered this problem when using the public static void Main(); and calling methods inside the same class. My code was as follows:

namespace TestingProject
{
    class Class1
    {
        public static void Main()
        {
            System.Console.WriteLine("This is nothing but a test \n Input 'test'");
            var UserInput = System.Console.ReadLine();
            string Input = this.ValidateInput(UserInput);
            System.Console.WriteLine(Input);
            System.Console.WriteLine();

        }
        protected string ValidateInput(string Variable)
        {
            var VarReturn = (string)null;
            if (string.Equals(Variable, "test"))
            {
                VarReturn = "Correct \n";
            }
            else
            {
                VarReturn = "Incorrect \n";
            }
            return VarReturn;
        }


    }
}

So, from what i've researched it turns out that you cannot use the this syntax to call internal private methods from a static function.

So I tried self but this returned no avail (assuming since languages such as python, PHP allow self ), so tried the following:

string Input = TestingProject.Class1.ValidateInput(UserInput);

To be presented with the following message:

Error 1 An object reference is required for the non-static field, method, or property 'TestingProject.Class1.ValidateInput(string)' C:\\Users\\xxx\\AppData\\Local\\Temporary Projects\\ClassProject\\Class1.cs 14 28 ClassProject

So then, I found this little gem which did solve the problem :

var CurrClass = new Class1();

and called the protected method as so:

var CurrClass = new Class1();
string Input = CurrClass.ValidateInput(UserInput);

Which did surprise me that this was the only available way to call internal non-staic private methods, so my overall question is:

Is there a way to call non-static methods which are protected/private without initializing a new variable to contain the current object?

The problem is that your Main method is static. A static method can not access non-static methods, even within the same class, without having an instance of the object. That is the entire point of having a static method: you don't have a concrete object to work with. It's outside of the scope of the other instance methods.

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