为什么有类级访问修饰符而不是对象级? [英] Why have class-level access modifiers instead of object-level?

查看:122
本文介绍了为什么有类级访问修饰符而不是对象级?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用C#时,我最近意识到我可以从 Foo 的静态调用 Foo 对象的私有函数函数,甚至来自其他 Foo 对象。在我学到了关于访问修饰符的一切后,这对我来说很奇怪。

While using C#, I recently realised that I can call a Foo object's private functions from Foo's static functions, and even from other Foo objects. After everything I have learned about access modifiers, this sounds very strange to me.

据我所知,当一个函数做某事时,种内部过程。只有对象本身知道何时使用这些函数,因为其他对象不应/不能控制对象的流。有什么理由为什么同一个类的其他对象应该被排除在这个相当简单的规则之外?

As far as I know, you make a function private when it does something that's part of some kind of internal process. Only the object itself knows when to use those functions, because other objects shouldn't/can't control the object's flow. Is there any reason why other objects of the same class should be excepted from this pretty straightforward rule?

根据请求,一个例子:

public class AClass {
    private void doSomething() { /* Do something here */ }
    public void aFunction() {
        AClass f = new AClass();
        f.doSomething(); // I would have expected this line to cause an access error.
    }
}


推荐答案

它可以是有用的,例如,如果你有一个Equals方法需要访问另一个实例的私有成员:

It can be useful for instance if you have an Equals method which needs access to another instance's private members:

public class AClass
{
    private int privateMemberA;

    // This version of Equals has been simplified
    // for the purpose of exemplifying my point, it shouldn't be copied as is
    public override bool Equals(object obj)
    {
        var otherInstance = obj as AClass;
        if (otherInstance == null)
        {
            return null;
        }

        return otherInstance.privateMemberA == this.privateMemberA;
    }
}

这篇关于为什么有类级访问修饰符而不是对象级?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆