[英]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();
我最近选择了C#作为另一种语言,以将我的知识进一步理解为其他语言,但是当尝试适应该语言的语法时,在使用
public static void Main();
时遇到了这个问题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. 因此,从我研究的结果来看,您不能使用
this
语法从静态函数调用内部私有方法。
So I tried self
but this returned no avail (assuming since languages such as python, PHP allow self
), so tried the following: 所以我尝试了
self
但是没有成功(假设由于python,PHP之类的语言允许self
),所以尝试了以下方法:
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
错误1非静态字段,方法或属性'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: 并这样调用了protected方法:
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. 问题是您的
Main
方法是静态的。 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.
它不在其他实例方法的范围内。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.