如何在C#中将修饰符设置为公共 [英] how to set modifiers as public in c#

查看:75
本文介绍了如何在C#中将修饰符设置为公共的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

//我已经创建了按钮控件

//I have created button control

public class myButton : System.Windows.Forms.Button
    {
       public myButton()
        {
          //.............
        }
    }



但是当我使用此按钮时,在属性修饰符=私有(默认)中
我希望作为修饰符=公共(默认)



but when I use this button, in property modifiers=private (default)
i want as modifiers=public (default)

推荐答案

作为一般规则,请勿将任何组件公开(或受保护).提示将导致设计错误的应用程序.

几乎没有正当的理由允许从表单外部访问表单中的控件.

将事件和属性添加到表单中,以获取需要获取或设置的一些属性以及需要处理的一些事件.

如果您允许公众访问按钮之类的组件,那么,如果重命名按钮或决定更改链接的按钮,您会认为会发生什么.

顺便说一下,更改并不难,因为设计人员(至少在C#中)允许您更改访问修饰符.这样做几乎没有意义.
As a general rule, don''t make any component public (or protected). Thiks will lead to badly designed application.

There are almost no valid reason to give access to a control in a form from the outside of the form.

Add events and properties to your form for the few properties you need to get or set and the few events you need to handle.

If you give public access to a component like a button, what do you think will happen if you rename the button or decide to change the button for a link.

By the way, it is not that hard to change that as the designer (at least in C#) allows you to change the access modifier. In rarely make sense to do so.


我同意,控件的public访问修饰符的想法非常糟糕.实际上,您实际上需要的是internal而不是public,但这也是一个坏主意.

如果您认为为什么需要更多访问权限,则将找到正确的解决方案.该问题被简化为表单协作的问题.最健壮的方法是在表单类中实现适当的接口.

有关更多详细信息,请参阅我过去的解决方案:如何以两种形式在列表框之间复制所有项目 [
I agree, the idea of public access modifier for a control is quite bad. You would actually need internal instead of public, but it''s also a bad idea.

The right solution will come if you think why would you need more access. The problem is reduced to the problem of form collaboration. The most robust approach is implementing appropriate interface in form class.

For more detail, see my past solution: How to copy all the items between listboxes in two forms[^]. Read all other suggestions and the discussion.

—SA


Visual Studio默认情况下将表单内的所有控件设为私有(有充分的理由). AFAIK,您不能在控制代码中更改此行为.公开它不是一个好主意.如果根本需要从表单外部访问它,则通过仅具有get访问器的公共属性来公开它.
Visual Studio by default makes all controls within a form private (and for good reasons). AFAIK, you cannot change this behavior in your control code. It is not a good idea to make it public. If at all you need to access it from outside the form, then expose it through a public property with only a get accessor.


这篇关于如何在C#中将修饰符设置为公共的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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