简体   繁体   English

C#中的OO问题

[英]OO Problem in C#

class Frame
{
    static int X;
    static int Y;
    static uint Color;

    static protected bool Check()
    {
        return (Coords.GetPixelColor(X, Y) == Color);
    }
}

class frameBeginning : Frame
{
    static int X = 1;
    static int Y = 2;
    static int Color = 3;
}

frameBeginning.Check(); cannot compile, because Check() is inaccessible due to its protection level. 无法编译,因为Check()由于其保护级别而无法访问。

But why, Check() is protected? 但为什么, Check()受到保护?

This is not a problem. 这不是问题。 The behavior you are seeing is part of the definition of protected . 您看到的行为是受保护定义的一部分。 If you want to call frameBeginning.Check from outside the code of the frameBeginning or frame class, the method needs to be public or internal . 如果要从frameBeginning或frame类的代码外部调用frameBeginning.Check,则该方法需要是publicinternal

Because you declared it as protected in the code shown above. 因为您在上面显示的代码中将其声明为受保护。

But different rules apply to static methods. 但是不同的规则适用于静态方法。 Check out the SO question below: 查看以下SO问题:

C#: Can a base class use a derived class's variable in a static function? C#:基类可以在静态函数中使用派生类的变量吗?

You could call Check from within frameBeginning , but not outside the class. 您可以 frameBeginning调用Check ,但不能在类外部调用。 This is what protected means: visible to derived classes, not to external code. 这就是protected含义:派生类可见,而不是外部代码。

Using frameBeginning.Check() from outside needs that Check() is public. 从外部使用frameBeginning.Check()需要Check()是公共的。 Being protected is only visible to derived clasess, but not from outside. 受保护只能由派生的clasess看到,但不能从外部看到。 You're trying to access the Check() method from outside, so you need to do Check() public or internal. 您正在尝试从外部访问Check()方法,因此您需要执行Check() public或internal。

In other words, you could acess Check() from a frameBeginning instance, but Check() is static, if you want to access Check() from outside, you need to change the visibility to public (or internal). 换句话说,您可以从frameBeginning实例访问Check() ,但Check()是静态的,如果要从外部访问Check(),则需要将可见性更改为public(或internal)。

这样类本身和所有继承的类都可以使用该方法,独立于对象的实例,但是类之外的任何东西都不能使用该方法。

There are 5 access modifiers... you need to understand what kind of access you can get by each. 有5个访问修饰符......你需要了解每个访问修改器可以获得什么样的访问权限。

private - Function can only be called from within the class private - 只能在类中调用函数

protected - Function can be called only from within the class and all its derived classes protected - 只能从类及其所有派生类中调用函数

internal protected - Function can be called by the class and all its derived classes inside the Assembly internal protected - 函数可以由类及其在Assembly中的所有派生类调用

internal - Almost like public - Can be called from anywhere inside the Assembly ... Used for Incapsulation internal - 几乎像public一样 - 可以从Assembly内部的任何地方调用...用于封装

public - Can be called from anywhere public - 可以从任何地方调用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM