内部带有私有方法的静态方法 [C#]
我想创建一个 类 Draw 它将具有静态方法 ConsoleSquare() 并且我想制作所有其他该类中的方法隐藏(private)。但是我在标记的地方遇到了错误,我不知道如何解决它们并仍然实现相同的想法(ConsoleSquare() - 静态;所有其他方法隐藏)
class Draw {
private string Spaces(int k){
string str="";
for(;k!=0;k--)
str+='\b';
return str;
}
private string Line(int n,char c){
string str="";
for(;n!=0;n--)
str+=c;
return str;
}
public static void ConsoleSquare(int n,char c){
string line = Line(n,c); // ovdje
string space = c + Spaces(n - 2) + c; //ovdje
Console.WriteLine(line);
for (; n != 0; n--)
Console.WriteLine(space);
Console.WriteLine(line);
}
}
I wanted to make a class Draw which will have static method ConsoleSquare() and I wanted to make all other methods in that class hidden (private).But I got errors in marked places and I don't know how to solve them and still achieve the same idea ( ConsoleSquare() - static ; all other methods hidden )
class Draw {
private string Spaces(int k){
string str="";
for(;k!=0;k--)
str+='\b';
return str;
}
private string Line(int n,char c){
string str="";
for(;n!=0;n--)
str+=c;
return str;
}
public static void ConsoleSquare(int n,char c){
string line = Line(n,c); // ovdje
string space = c + Spaces(n - 2) + c; //ovdje
Console.WriteLine(line);
for (; n != 0; n--)
Console.WriteLine(space);
Console.WriteLine(line);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
除非您显式提供实例,否则静态方法无法调用实例方法。如果您想直接从
ConsoleSquare
调用,请将Spaces
和Line
标记为静态。A static method cannot call instance methods unless you explicitly provide an instance. Mark
Spaces
andLine
as static as well if you want to call these directly fromConsoleSquare
.将它们声明为
私有静态
。Declare them as
private static
.您需要一个实例来调用实例方法。如果不提供实例,则无法从静态方法调用实例方法。
you need an instance to call an instance method. You can't call an instance method from a static method without providing an instance.
也将私有方法设为静态。
Make the private methods static too.
我建议您将所有与 Draw 相关的方法封装在另一个类中。不要在那里放置任何静态方法。让所有方法也都公开。
定义另一个类;称之为
DrawUI
或其他名称。让其具有静态方法。在此静态方法中实例化Draw
类,使用其方法I would suggest you encapsulate all
Draw
related methods in another class. Don't put any static method in there. Let all the methods be public in that too.Define another class; call it
DrawUI
or something. Let this have the static method. In this static method instantiate theDraw
class, use its methods