C# 可访问性不一致(Inconsistent accessibility)

最新经常碰到这个报错:

error CS0051: Inconsistent accessibility: parameter type XXX is less accessible than method XXX’
error CS0051: 可访问性不一致: 参数类型XXX的可访问性低于方法XXX

原因是:

The return type and each of the types referenced in the formal parameter list of a method must be at least as accessible as the method itself. Make sure the types used in method signatures are not accidentally private due to the omission of the public modifier. For more information, see Access Modifiers.
方法的返回类型和引用参数的类型的可访问性不能低于方法的可访问性。注意,不要因为忘记用public修饰【函数签名中用到的类型】而导致其类型是private。(我猜指的是class和struct成员默认为private)

举个栗子:

class MyClass
{
    struct User
    {
        string name;
        int age;
        bool gender;       
    }

    public void Foo(User user) //error CS0051
    {
        user.name   = "miao";
        user.age    = 10;
        user.gender = true;
    }
}

方法Foo的可访问性为public,有一个引用参数user为User类型,而User是MyClass的成员,默认访问性为private低于方法Foo的可访问性,所以会报【可访问性不一致】的错误。

修改方法无非就两种,提高User的可访问性到public(试了一下internal也可以)或者减低方法Foo可访问性到private。

实际上,上面的代码还有一个错误【error CS0122: `main.User.name’ is inaccessible due to its protection level】:

user.name   = "miao"; //error CS0122
user.age    = 10;     //error CS0122
user.gender = true;   //error CS0122

struct 的成员默认的可访问性为private,所以不可见。
可能有人会问这不是在同一个对象吗?实际上,并不是这样。因为这个user并不是MyClass的成员,只是一个本地变量。

最后附两个参考链接:
MSDN可访问性级别
编译错误代码解释

猜你喜欢

转载自blog.csdn.net/guojunxiu/article/details/81292235