为什么我们使用 public 方法?

Why do we use public methods?

我有一个关于 public 和静态方法的问题。我是 C# 编码的新手,我知道 public 方法只能使用对象访问。但是,可以在没有 class 的对象的情况下访问静态方法。但是使用 public 方法有什么意义呢?为什么不总是使用静态方法?

publicstatic 关键字不相关。

你可以有一个public static方法。 Public 表示该方法(或其他 class 成员(例如 属性、字段、委托、枚举、内部 class))可供使用通过属于另一个 class 的代码(备选方案是 privateinternal 和一些组合)。

static 关键字表示访问该成员不需要 class 的实例。在某些方面,您可以将 static 成员视为 属于 到 class 而非静态成员 属于 ] 到 class 的实例。 VB 语言强调该隐喻,使用 Shared 而不是 static 来描述静态成员(以强调静态成员在 class 的所有成员之间共享)。

使用非静态成员有很大的优势(查找 封装 - 这是一个很好的面试流行语)。面向对象的思维定式是一个对象代表一个数据结构(C#中的classstruct)和操作这可以在该数据结构上完成。这些操作是 class.

的非静态方法

我觉得Flydog57的回答更完整。在我的回答中,我将添加代码示例,希望能让它更容易理解。

Public - 访问修饰符,决定从哪里可以访问您的代码 (method/class/etc.)。 Public 没有任何限制,因此您基本上可以从任何地方访问您的代码。另一方面,如果方法或 属性 或其他东西是 private,您只能从它所属的 class 中访问它。还有其他访问修饰符,请查看 here.

Static - static 是一个修饰符关键字,它决定了你的方法,属性 等应该使用 class 的对象访问,或者应该直接使用 class 访问名字.

在下面的代码中,加法是静态的,但减法不是静态的。所以,我们只能用对象访问减法。为了访问添加,我们需要使用 class 名称“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;
    }
}

现在,如果我们删除 public 访问修饰符。我们得到以下错误。因为无法再从 class 外部访问这些方法。在这里查看 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
    }
}

你什么时候使用它们: 这两者都有很多用例。在下面的示例中,我使用 static 属性 TotalStudent 来计算学生(对象)的总数。当我使用 Name 属性 来保留特定对象独有的信息时。也像上面的数学示例 c# 和许多其他编程语言都有 Math static class 可以让你做加法和其他操作。

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
    }
}