C# 我什么时候应该使用公共/私有/静态方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/793494/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 01:21:34  来源:igfitidea点击:

When should I use public/private/static methods?

c#vb.net

提问by Ivan Prodanov

I'm new to C#.Till this moment I used to make every global variable - public static.All my methods are public static so I can access them from other classes.

我是 C# 的新手。直到这一刻,我习惯于将每个全局变量 - 公共静态。我所有的方都是公共静态的,所以我可以从其他类访问它们。

I read on SO that the less public static methods I have,the better.So I rewrote my applications by putting all the code in one class - the form class.Now all my methods are private and there's no static method.

我读到,我拥有的公共静态方越少越好。所以我重写了我的应用程序,将所有代码放在一个类中 - 表单类。现在我所有的方都是私有的,没有静态方。

My question: What should I do,keeping everything in the form class is dump in my opinion.

我的问题:我应该怎么做,在我看来,将所有内容保留在表单类中都是垃圾。

When should I use public,when private and when static private/public?

我什么时候应该使用公共,什么时候私有,什么时候使用静态私有/公共?

I get the public methods as a 'cons' ,because they can be decompiled,but I doubt that.My public methods can be decompiled too.What is so 'private' in a private method?

我将公共方视为“缺点”,因为它们可以反编译,但我对此表示怀疑。我的公共方也可以反编译。私有方中的“私有”是什么?

EDIT: I'm not asking how to prevent my program to be decompiled,I'm asking whether I should use static,private and public.And also : Is there are problem in putting all the code in the form class so I dont have to use public methods?

编辑:我不是在问如何防止我的程序被反编译,我是在问我是否应该使用静态、私有和公共。还有:将所有代码放在表单类中是否有问题,所以我没有使用公共方?

采纳答案by TStamper

private is for class members that you want only access within the class of the body, and in C# members are default set to private unless specified different

private 用于只希望在主体类内访问的类成员,在 C# 中,成员默认设置为私有,除非指定不同

examples of when to use private:

何时使用私有的示例:

class Account
{

  private int pin = 1090;
  public int Pin
  {
     get { return pin; }
  }
}

public on the other hand is the opposite, there are no restrictions with accessing public members, so when things that don't matter with the user having access to should be public.

另一方面,public 恰恰相反,访问公共成员没有任何限制,因此当与用户有权访问无关的事情应该公开时。

static on the other hand has no relation to the two, because it doesn't deal with permission to methods, static on the other hand is a constant or type declaration. If the word static is applied to the class then every member in the class must be declared static.

另一方面,静态与两者没有关系,因为它不处理方的权限,另一方面,静态是常量或类型声明。如果静态一词应用于类,则类中的每个成员都必须声明为静态。

examples of when to use static:

何时使用静态的示例:

  static int birth_year= 1985

Modifiers in C# Referencewill give you more detail of all modifiers in C# and examples of how they should be used

C# 参考中的修饰符将为您提供有关C#中所有修饰符的更多详细信息以及如何使用它们的示例

回答by Anton Gogolev

See Access Modifiers (C# Programming Guide). But it's be far better if you got yourself a decent C# and OOP/OOD book: these are really basics of computer science.

请参阅访问修饰符(C# 编程指南)。但是如果你自己有一本像样的 C# 和 OOP/OOD 书,那就更好了:这些都是计算机科学的真正基础。

Long story short: access modifiers promote encapsulation, which basically means that every class should keep its privates to itself.

长话短说:访问修饰符促进了封装,这基本上意味着每个类都应该保持自己的私有。

回答by Stefan Kendall

This seems more basic than the question linked above. To properly thrive in an OO language, you'll need to figure out how to decompose your end goal into a series of objects that work together (even containing and extending one another) to achieve a series of goals. This abstraction has numerous benefits which become apparent once you begin properly implementing OO design. You're going to want a new C# book, as mentioned, if you haven't already gotten to the part explaining the basics of Object Oriented Programming.

这似乎比上面链接的问题更基本。为了在 OO 语言中正常发展,您需要弄清楚如何将您的最终目标分解为一系列协同工作(甚至相互包含和扩展)以实现一系列目标的对象。这种抽象有许多好处,一旦您开始正确实施 OO 设计,这些好处就会变得显而易见。你会希望有一个新的C#的书,如前所述,如果你还没有已经得到的部分解释的基础Øbject Øriented编程。

回答by Stefano Borini

Everything should be private unless proven otherwise. The difference between public and private is between what is supposed to be kept compatible and what is not supposed to be kept compatible, what is supposed to be interesting to the world and what is not supposed to be its business.

除非另有证明,否则一切都应该是私有的。公共和私人之间的区别在于应该保持兼容的和不应该保持兼容的,应该对世界感兴趣的和不应该是它的业务的。

When you declare something public, the class (and consequently the object) is making a strong statement: this is my visible interface, there are many other like this, but this is mine. The public interface is a contractual agreement that your class is exporting to the rest of the world (whatever that means) about what it can do. If you modify the public interface, you risk breaking the contract that the rest of the world is assuming about the class.

当你声明一些公共的东西时,类(以及对象)正在做出一个强有力的声明:这是我的可见界面,还有很多其他类似的,但这是我的。公共接口是您的类向世界其他地方(无论这意味着什么)输出的关于它可以做什么的合同协议。如果您修改公共接口,您可能会违反世界其他地方对该类的假设。

On the other hand, private stuff is internal to the class. It supports functionality that the class must use to do its job while carrying the object state around (if it's a method) or keeping its internal state (if it's a variable). You are free to hack and tinker the class private stuff as much as you want, without breaking the interface contract, meaning that this gives you wide freedom for refactoring (of the internal data representation, for example, for efficiency). Private stuff is not part of the interface.

另一方面,私有的东西是班级内部的。它支持类在携带对象状态(如果它是一个方)或保持其内部状态(如果它是一个变量)时必须用来完成其工作的功能。您可以随意修改和修改类私有内容,而不会破坏接口契约,这意味着这为您提供了广泛的重构自由(例如,为了提高效率,内部数据表示)。私有的东西不是界面的一部分。

Protected is something that involves the openness to reimplementation. Avoid, if you can, deeply nested inheritances. You risk making things very difficult to handle, as your reimplementation class can screw the base class.

受保护的东西涉及重新实现的开放性。如果可以,请避免深度嵌套的继承。您冒着使事情变得非常难以处理的风险,因为您的重新实现类可能会破坏基类。

Technically, a class should declare an interface (public) and an implementation (private). The interface should not have code at all, just delegate to the private "implementation" logic. This is why in Java and C# you have interface statement, which formalizes the pure abstract class concept in C++.

从技术上讲,一个类应该声明一个接口(公共)和一个实现(私有)。接口根本不应该有代码,只是委托给私有的“实现”逻辑。这就是为什么在 Java 和 C# 中有 interface 语句的原因,它将 C++ 中的纯抽象类概念形式化。

Static is something that resides logically in the realm of your class but does not depend on the state of the class itself. It should be used sparingly when a design pattern dictates it (e.g., singleton, factory method).

静态是逻辑上驻留在类领域中的东西,但不依赖于类本身的状态。当设计模式规定它时,应该谨慎使用它(例如,单例、工厂方)。

回答by Tom

All is answered above already, but I think it could be simplified a bit... so decorate a method public, if other classes will be using this method. If not - mark it private.

上面已经回答了所有问题,但我认为它可以简化一点......所以如果其他类将使用这个方,那么装饰一个公共方。如果没有 - 将其标记为私有。

For instance you have Class Aand Class B. Say Class Ahas 3 methods (x,y,z). Methods x, ywill be used by Class B, so mark them both public, but method zwill be only be used by method xinside Class Aso mark it private as there's no need to be exposing this method to the external world. The logic inside this method is intended for internal use only.

例如,您有Class AClass B。假设A 类有 3 个方 (x,y,z)。方X,Y将通过使用B级,所以将它们标记为公共的,但方ž将仅由中使用X内部A级所以其标记为私有,因为没有必要将公开此方外部世界。此方中的逻辑仅供内部使用。

Static is differentl this decoration means you cannnot create an instance of an object marked static. The object is - as the keyword says - static(cannot be changed or modified).

静态是不同的,这种装饰意味着您不能创建标记为静态的对象的实例。对象是 - 正如关键字所说 -静态的(不能更改或修改)。

回答by vel murugan

Java provides a number of access modifiers to set access levels for classes, variables, methods and constructors. The four access levels are:

Java 提供了许多访问修饰符来设置类、变量、方和构造函数的访问级别。这四个访问级别是:

Visible to the package, the default. No modifiers are needed.

对包可见,默认。不需要修改器。

Visible to the class only (private).

仅对班级可见(私有)。

Visible to the world (public).

对世界可见(公共)。

Visible to the package and all subclasses (protected).

对包和所有子类可见(受保护)。

Here is an example:

下面是一个例子:

public class Bicycle {

公共课自行车{

private int cadence;
private int gear;
private int speed;
private int id;
private static int numberOfBicycles = 0;

public Bicycle(int startCadence, int startSpeed, int startGear){
    gear = startGear;
    cadence = startCadence;
    speed = startSpeed;

   id = ++numberOfBicycles;
}

// new method to return the ID instance variable
public int getID() {
    return id;
}
    ...

}

}

回答by Richard Luo

In addition to the above, think about working scenario. You are not working alone. Your peer fellow might call the methods from your class which you actually don't want to expose, or think it needs critical changes in the future. That might be the case you want a private

除了上述之外,请考虑工作场景。你不是一个人工作。您的同行可能会从您的类中调用您实际上不想公开的方,或者认为它将来需要进行重大更改。这可能是你想要一个私人的情况