Is there a C# equivalent to access-modifier regions in C++

不羁的心 提交于 2019-12-10 18:29:10

问题


It's possible to declare variables with the below structure in C++

private:
public:
protected:
    float bla1;
    float bla2;
    float bla3;

Is there an equivalent in C#? It seems rather tedious having to repeat yourself;

protected float bla1;
protected float bla2;
protected float bla3;

回答1:


No there isn't such a thing. In fact, it's designed to be like that to make code more readable. This applies to both C# and Java.




回答2:


No. The access is specified on each declaration.

The benefit of this is that a method's location within the source file has no effect on the behaviour. That means you can move methods and properties around (e.g. to cluster related methods together) with impunity. The same isn't quite true of fields - it's possible to make the declaration order of fields matter. Admittedly it's best not to do that in the first place...




回答3:


It's worth noting that if you have several members of the same type, you can declare them as:

protected float bla1, bla2, bla3;



回答4:


No there is no equivalent in C# (VB and F# as well).

Personally I love this difference. I work in a very large C++ code base and there is no way to look at a particular method and know it's particular accessibility. Some of the classes have gotten so large that it takes a significant amount of page scrolling just to see the modifier.

Some coders may think that's not to bad but consider what happens when people start mixing in #if defs in the middle of the class and adding modifiers within those #if's. It makes determining the access modifier during a code review a non-trivial operation.

It's a small typing sacrifice to add the modifier inline but worth it in terms of long term readability.



来源:https://stackoverflow.com/questions/431091/is-there-a-c-sharp-equivalent-to-access-modifier-regions-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!