C# 中的 void 与私有 void
本文关键字:void 中的 | 更新日期: 2024-10-20 00:53:16
在 C# UI 代码中,当我创建事件方法时,它会自动填充
void simpleButton_click(object sender, Eventargs e)
{
}
这个简单的void
和private void
有什么区别?
没有,它是语法的。默认情况下,成员private
,而类型internal
(。
通常,人们为了保持一致性而添加private
,尤其是当它位于具有许多其他具有不同访问属性(如 protected internal
或 public
(的成员的类或类型中时。
因此,以下两个文件是等效的:
隐式.cs
using System;
namespace Foo
{
class Car : IVehicle
{
Car(String make)
{
this.Make = make;
}
String Make { get; set; }
CarEngine Engine { get; set; }
void TurnIgnition()
{
this.Engine.EngageStarterMotor();
}
class CarEngine
{
Int32 Cylinders { get; set; }
void EngageStarterMotor()
{
}
}
delegate void SomeOtherAction(Int32 x);
// The operator overloads won't compile as they must be public.
static Boolean operator==(Car left, Car right) { return false; }
static Boolean operator!=(Car left, Car right) { return true; }
}
struct Bicycle : IVehicle
{
String Model { get; set; }
}
interface IVehicle
{
void Move();
}
delegate void SomeAction(Int32 x);
}
明确.cs
using System;
namespace Foo
{
internal class Car : IVehicle
{
private Car(String make)
{
this.Make = make;
}
private String Make { get; set; }
private CarEngine Engine { get; set; }
private void TurnIgnition()
{
this.Engine.EngageStarterMotor();
}
private class CarEngine
{
private Int32 Cylinders { get; set; }
private void EngageStarterMotor()
{
}
}
private delegate void SomeOtherAction(Int32 x);
public static Boolean operator==(Car left, Car right) { return false; }
public static Boolean operator!=(Car left, Car right) { return true; }
}
internal struct Bicycle : IVehicle
{
private String Model { get; set; }
}
internal interface IVehicle
{
public void Move(); // this is a compile error as interface members cannot have access modifiers
}
internal delegate void SomeAction(Int32 x);
}
规则摘要:
- 默认情况下,直接在
namespace
中定义的类型(class
、struct
、enum
、delegate
、interface
(是internal
的。 - 默认情况下
private
成员(方法、构造函数、属性、嵌套类型、事件(,但有两个例外:- 运算符重载必须显式标记为
public static
。如果未提供显式public
访问修饰符,则会收到编译错误。 - 接口成员始终
public
,不能提供显式访问修饰符。
- 运算符重载必须显式标记为
- 在 C# 中,默认情况下
private
class
和struct
成员,这与C++不同,struct
默认public
,默认class
private
。 - 在 C# 中,没有任何内容是隐式
protected
或protected internal
的。 - .NET 支持"友元程序集",其中
internal
类型和成员对另一个程序集中的代码可见。C# 需要[assembly: InternalsVisibleTo]
属性才能实现此目的。这与C++的friend
功能不同(C++的friend
允许class
/struct
列出可以访问其private
成员的其他类,结构和自由函数(。
void 表示将此代码或过程块标识为方法,否则它不会返回任何值。 如果您看到任何类型而不是 void 意味着代码或过程的阻止是函数或属性
这是方法
private void DoSomething()
{
...code
}
这是功能
private int DoSomething()
{
..code
return 1
}
private 意味着方法、函数或属性不能在类外部访问,但可以在类本身内部调用
public 意味着方法、函数或属性可供类外部访问,也可以在类本身内部调用