在C#用户界面代码中,当我创建事件方法时,它将自动填充到
void simpleButton_click(object sender, Eventargs e)
{
}
这个简单的void
和private void
有什么区别?
发布于 2013-12-17 02:44:03
不,这是句法。默认情况下,成员是private
,而类型是internal
)。
通常,为了保持一致性,人们会添加private
,特别是当它位于具有不同访问属性的其他成员的类或类型中时,例如protected internal
或public
。
因此,以下两个文件是等效的:
Implicit.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);
}
Explicit.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);
}
“规则”摘要:
class
、struct
、enum
、delegate
、interface
中直接定义的类型是internal
。private
,但有两个例外:public static
。如果不提供显式的public
访问修饰符,您将得到编译错误。public
,您不能提供显式访问修饰符。
class
和struct
成员在默认情况下都是private
,与C++不同,C++默认为public
,class
默认为private
。protected
中,没有任何东西是隐式的protected internal
或protected internal
。internal
类型和成员在另一个程序集中的代码中是可见的。C#需要[assembly: InternalsVisibleTo]
属性来实现这一点。这与C++的friend
特性不同(C++的friend
允许class
/struct
列出将访问其private
成员的其他类、结构和自由函数)。发布于 2013-12-17 03:10:07
void意味着将这段代码或过程标识为方法,否则它将不返回任何值。如果您看到任何类型而不是空,则意味着代码或过程的阻塞是一个函数或属性。
这就是方法
private void DoSomething()
{
...code
}
这是函数
private int DoSomething()
{
..code
return 1
}
私有是指方法、函数或属性是,不能访问类外部的,但可以在类本身内调用。
public是指方法、函数或属性是类外部的可访问的,也可以在类本身内调用。
https://stackoverflow.com/questions/20624950
复制相似问题