enum Gender
{
男,女
}
代码:
public struct Person
{
public string name;
public Gender sex;
public int age;
}
public class Program
{
static void Main(string[] args)
{
Person person;
person.name = "张三";
person.sex = Gender.男;
person.age = 25;
Console.WriteLine("请显示他们的信息{0},{1},{2}岁", person.name, person.sex, person.age);
Console.ReadKey();
}
}
class BaseClass {...}
public class MyClass: BaseClass {...} // Error
下表汇总了对使用声明的可访问性级别的限制。
上下文
备注
类
类类型的直接基类必须至少与类类型本身具有同样的可访问性。
接口
接口类型的显式基接口必须至少与接口类型本身具有同样的可访问性。
委托
委托类型的返回类型和参数类型必须至少与委托类型本身具有同样的可访问性。
常数
常数的类型必须至少与常数本身具有同样的可访问性。
字段
字段的类型必须至少与字段本身具有同样的可访问性。
方法
方法的返回类型和参数类型必须至少与方法本身具有同样的可访问性。
属性
属性的类型必须至少与属性本身具有同样的可访问性。
事件
事件的类型必须至少与事件本身具有同样的可访问性。
索引器
索引器的类型和参数类型必须至少与索引器本身具有同样的可访问性。
运算符
运算符的返回类型和参数类型必须至少与运算符本身具有同样的可访问性。
构造函数
构造函数的参数类型必须至少与构造函数本身具有同样的可访问性。
下面的示例包含不同类型的错误声明。每个声明后的注释指示了预期的编译器错误。
// Restrictions_on_Using_Accessibility_Levels.cs
// CS0052 expected as well as CS0053, CS0056, and CS0057
// To make the program work, change access level of both class B
// and MyPrivateMethod() to public.
using System;
// A delegate:
delegate int MyDelegate();
class B
{
// A private method:
static int MyPrivateMethod()
{
return 0;
}
}
public class A
{
// Error: The type B is less accessible than the field A.myField.
public B myField = new B();
// Error: The type B is less accessible
// than the constant A.myConst.
public readonly B myConst = new B();
public B MyMethod()
{
// Error: The type B is less accessible
// than the method A.MyMethod.
return new B();
}
// Error: The type B is less accessible than the property A.MyProp
public B MyProp
{
set
{
}
}
MyDelegate d = new MyDelegate(B.MyPrivateMethod);
// Even when B is declared public, you still get the error:
// "The parameter B.MyPrivateMethod is not accessible due to
// protection level."
public static B operator +(A m1, B m2)
{
// Error: The type B is less accessible
// than the operator A.operator +(A,B)
return new B();
}