看看这个C#代码哪有问题啊?

来源:百度知道 编辑:UC知道 时间:2024/06/22 09:52:40
class TextMethod
{
int square(int x)
{
return x * x;
}

double square(double x)
{
return x * x;
}
decimal square(decimal x)
{
return x * x;
}

}
static void Main(string[] args)
{
TextMethod t = new TextMethod();
Console.WriteLine("The square is{0},{1},{2}",t.square(10),t.square(12,34),t.square(123,456m));
}

它说: “TextMethod.TextMethod.square(int)”不可访问,因为它受保护级别限制 D:\C#\C#-----LinJie\TextMethod\TextMethod\Program.cs 12 73 TextMethod

你的Main是放在TextMethod类外面的,而你的方法前面没有修饰符,默认是Private类型,也就是私有类型,不可被外部访问。
有两个解决办法。
1.把static void Main(string[] args) 放到TextMethod类里面。
2.在方法前面添加public修饰符,变成:

public int square(int x)
{
return x * x;
}

public double square(double x)
{
return x * x;
}
public decimal square(decimal x)
{
return x * x;
}