在C# UI代码中,当我创建事件方法时,它会自动填充以下内容:
这个简单的
void simpleButton_click(object sender, Eventargs e)
{
}
这个简单的
void
和 private void
有什么区别呢?这是语法问题。默认情况下,成员是 private
的,而类型是 internal
的。
通常人们为了保持一致性会添加 private
,特别是在一个类或类型中有许多其他访问属性不同的成员(例如 protected internal
或 public
)时。
因此,以下两个文件是等效的:
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);
}
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
,您无法提供显式访问修饰符。class
和 struct
成员默认为 private
,而不像 C++ 中 struct
默认为 public
,class
默认为 private
。protected
或 protected internal
。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 表示该方法、函数或属性可被外部类访问,并且也可以在类内部调用。