C#访问修饰符

[文章] 浏览(48)  | 2016年12月08日  | 支持服务 | 
[标签]C#

C#共有五种访问修饰符

public、private、protected、internal、protected internal。作用范围如下表:

访问修饰符(级别) 说明
public  公有访问。不受任何限制。
同一程序集的其他任何代码或引用该程序集的其他程序集都可以访问该类型或成员
private 私有访问。只限于本类成员访问,子类,实例都不能访问。
protected 保护访问。只限于本类和子类访问,实例不能访问。
internal 内部访问。只限于本项目内访问,其他不能访问。
同一程序集中的任何代码都可以访问该类型或成员,但其他程序集不可以访问。
protected internal 内部保护访问。只限于本项目或是子类访问,其他不能访问

C#成员类型的可修饰及默认修饰符如下表:

成员类型 默认修饰符 可被修饰符 默认访问修饰符
enum public none  
class private public、protected、internal、private、
protected internal
 
interface public none  
struct private public、internal、private  
方法 private   internal
变量 private   internal

public、private、protected、internal和protected internal的作用范围。

 C#的方法的参数修饰符

参数无修饰:其参数传递的方式是值传递,接受方收到的是原始数据的拷贝。

out:输出参数,参数是引用传递。方法内必须赋值out参数,并且,方法内未被赋值前,不可使用!

params 可变参,注意了这种修饰符针对的参数一定是最后一个参数

ref 引用传递,参数的内容会改变。调用方法前,必须赋值。方法内改变ref参数,调用方法完成后,也同样改变。

// 缺省是传值
public static int Add(int x, int y)
{
    int ans = x + y;
    x = 10000;
    y = 88888;
    return ans;
}

static void Main(string[] args)
{
    int x = 9, y = 10;
    Console.WriteLine("调用前: X: {0}, Y: {1}", x, y);
    Console.WriteLine("结果: {0}", Add(x, y));
    Console.WriteLine("调用后: X: {0}, Y: {1}", x, y);
}

// 输出修饰
public static void Add(int x, int y, out int ans)
{
    ans = x + y;
}

static void Main(string[] args)
{
    // 不需要进行本地赋值
    int ans;
    Add(90, 90, out ans);
    Console.WriteLine("90 + 90 = {0} ", ans);
}

// 多个输出修饰
public static void FillTheseValues(out int a, out string b, out bool c)
{
    a = 9;
    b = "Enjoy your string.";
    c = true;
}

static void Main(string[] args)
{
    int i;
    string str;
    bool b;
    FillTheseValues(out i, out str, out b);
    Console.WriteLine("Int is: {0}", i);
    Console.WriteLine("String is: {0}", str);
    Console.WriteLine("Boolean is: {0}", b);
}

//引用修饰
public static void SwapStrings(ref string s1, ref string s2)
{
    string tempStr = s1;
    s1 = s2;
    s2 = tempStr;
}
//This method can be called as so:
static void Main(string[] args)
{
    string s = "第一个字符串";
    string s2 = "其他字符串";
    Console.WriteLine("之前: {0}, {1} ", s, s2);
    SwapStrings(ref s, ref s2);
    Console.WriteLine("之后: {0}, {1} ", s, s2);
}

//可变参
static double CalculateAverage(params double[] values)
{
    double sum = 0;
    for (int i = 0; i < values.Length; i++)
    sum += values[i];
    return (sum / values.Length);
}

static void Main(string[] args)
{
    // Pass in a comma-delimited list of doubles...
    double average;
    average = CalculateAverage(4.0, 3.2, 5.7);
    Console.WriteLine("4.0, 3.2, 5.7 的平均数是: {0}",average);
    double[] data = { 4.0, 3.2, 5.7 };
    average = CalculateAverage(data);
    Console.WriteLine("Average of data is: {0}", average);
    Console.ReadLine();
} 
附件说明
附件