微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

C#中的void vs private void

在C#UI代码中,当我创建事件方法时,它会自动填充

void simpleButton_click(object sender,Eventargs e)
{
}

这个简单的虚空和私有虚空之间有什么区别?

解决方法

没有,这是语法上的.认情况下,成员是私有的,而类型是内部的.

通常人们为了一致性而添加私有,特别是当它在具有不同访问属性的许多其他成员的类或类型中时,例如受保护的内部或公共.

所以以下两个文件是等价的:

Implicit.cs

using System;

namespace Foo
{
    class Car : IVehicle
    {
        Car(String make)
        {
            this.Make = make;
        }

        String Make { get; set; }

        CarEngine Engine { get; set; }

        void TurnIgnition()
        {
            this.Engine.EngageStarterMotor();
        }

        class CarEngine
        {
            Int32 Cylinders { get; set; }

            void EngageStarterMotor()
            {
            }
        }

        delegate void SomeOtherAction(Int32 x);

        // The operator overloads won't compile as they must be public.
        static Boolean operator==(Car left,Car right) { return false; }
        static Boolean operator!=(Car left,Car right) { return true; }
    }

    struct Bicycle : IVehicle
    {
        String Model { get; set; }
    }

    interface IVehicle
    {
        void Move();
    }

    delegate void SomeAction(Int32 x);
}

Explicit.cs

using System;

namespace Foo
{
    internal class Car : IVehicle
    {
        private Car(String make)
        {
            this.Make = make;
        }

        private String Make { get; set; }

        private CarEngine Engine { get; set; }

        private void TurnIgnition()
        {
            this.Engine.EngageStarterMotor();
        }

        private class CarEngine
        {
            private Int32 Cylinders { get; set; }

            private void EngageStarterMotor()
            {
            }
        }

        private delegate void SomeOtherAction(Int32 x);

        public static Boolean operator==(Car left,Car right) { return false; }
        public static Boolean operator!=(Car left,Car right) { return true; }
    }

    internal struct Bicycle : IVehicle
    {
        private String Model { get; set; }
    }

    internal interface IVehicle
    {
        public void Move(); // this is a compile error as interface members cannot have access modifiers
    }

    internal delegate void SomeAction(Int32 x);
}

规则摘要

>认情况下,直接在命名空间中定义的类型(类,结构,枚举,委托,接口)是内部的.
>认情况下,成员(方法,构造函数,属性,嵌套类型,事件)是私有的,但有两个例外:

>必须将operator-overloads明确标记为public static.如果您不提供显式公共访问修饰符,则会出现编译错误.
>接口成员始终是公共的,您无法提供显式访问修饰符.

>在C#中,认情况下,类和结构成员都是私有的,与C不同,认情况下struct是public,认情况下class是private.> C#内部没有任何内容被隐式保护或保护.> .NET支持“朋友程序集”,其中内部类型和成员对另一个程序集内的代码可见. C#需要[assembly:InternalsVisibleto]属性来实现这一点.这与C的朋友特征不同(C的朋友允许类/结构列出可以访问其私有成员的其他类,结构和自由函数).

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐