我认为 Flydog57 的回答要完整得多。在我的回答中,我将添加代码示例,希望它更容易理解。
Public - 访问修饰符,用于确定可以从何处访问您的代码(方法/类/等)。 Public 没有任何限制,因此您基本上可以从任何地方访问您的代码。另一方面,如果一个方法或属性或其他东西是private,您只能从它所属的类中访问它。还有其他访问修饰符,请查看here。
静态 - 静态是一个修饰符关键字,它决定了你的方法、属性等应该使用类的对象访问还是应该直接使用类名访问。
在下面的代码中,加法是静态的,但减法不是静态的。所以,我们只能用对象访问减法。为了访问 Add,我们需要使用类名“Math.AddAdd(5, 4)”。注意:输出在评论中给出。
class Math
{
public static int Add(int a, int b)
{
return a + b;
}
public int Subtraction(int a, int b)
{
return a - b;
}
}
class Program
{
static void Main(string[] args)
{
Math math = new Math();
Console.WriteLine(math.Subtraction(10,4)); // 6
Console.WriteLine(math.Add(5, 4)); // Error CS0176 Member 'Math.Add(int, int)' cannot be accessed with an instance reference;
}
}
现在,如果我们删除公共访问修饰符。我们得到以下错误。因为不再可以从类的外部访问这些方法。看看这里看看default access modifiers of different types。
class Math
{
static int Add(int a, int b)
{
return a + b;
}
int Subtraction(int a, int b)
{
return a - b;
}
}
class Program
{
static void Main(string[] args)
{
Math math = new Math();
Console.WriteLine(math.Subtraction(5, 4)); // Error CS0122 'Math.Subtraction(int, int)' is inaccessible due to its protection level
Console.WriteLine(math.Add(5, 4)); // Error CS0122 'Math.Subtraction(int, int)' is inaccessible due to its protection level
}
}
您何时使用它们:
这两者都有很多用例。在下面的示例中,我使用静态属性 TotalStudent 来计算学生(对象)的总数。虽然我使用 Name 属性来保留该特定对象独有的信息。同样像上面的数学示例 c# 和许多其他编程语言都有 Math 静态类,可以让您进行求和、加法和其他操作。
class Student
{
public string Name { get; set; }
public static int TotalStudent { get; set; } = 0;
public Student(string name)
{
Name = name;
TotalStudent++;
}
}
class Program
{
static void Main(string[] args)
{
Student s1 = new Student("Bob");
Console.WriteLine(s1.Name); // Bob
Console.WriteLine(Student.TotalStudent); // 1
Student s2 = new Student("Alex");
Console.WriteLine(s2.Name); // Alex
Console.WriteLine(Student.TotalStudent); // 2
}
}