C#中的嵌套类
我正在尝试研究c#中的嵌套类.在阅读了许多文档和goggling之后,我还不清楚何时使用嵌套类.但据我所知,我做了一个小样本程序.我在下面粘贴我的代码.这个嵌套类程序是否以正确的逻辑实现? .实际上嵌套类用于什么?而且我对这个程序有疑问,我在程序中指出了这个疑问.请帮我 …
public partial class Form1 : Form { public Form1() { InitializeComponent(); Bank bankObj = new Bank(); bankObj.CreateAccount(); bankObj.ShowMyAccountNumber(); } } class Bank { static int accountNumber; // here if I just declare this as int accountNumber without static it showing an error in the CreatePersonalAccount(int accNo) method's first line ie accountNumber = accNo; as "Cannot access a non-static member of outer type." What actually this error mean ? public class BankAccountSection { public bool CreatePersonalAccount(int accNo) { accountNumber = accNo; return true; } } public void CreateAccount() { bool result = new BankAccountSection().CreatePersonalAccount(10001); } public void ShowMyAccountNumber() { MessageBox.Show(accountNumber.ToString()); } } 解决方法
嵌套类通常用于在封闭(外部)类之外没有用的小实用程序类.因此,嵌套类通常是私有的. (甚至还有
FxCop rule.)
你的代码 在您的情况下,嵌套类BankAccountSection并不真正有用,因为它本身没有状态. CreatePersonalAccount也可能只是外部类的一个方法. 关于static int accountNumber;:这将使accountNumber成为所有Bank对象的共享字段,这会破坏整个目的.不要那样做.如果确实需要在内部类中设置Bank对象的字段,则需要将Bank对象的引用传递给内部类. (这与Java不同,在某些情况下可以自动获得这样的引用.)在您的特定情况下,只需删除内部类. 合法用例的示例 >您在方法中有一个大型算法.您意识到使用许多小方法和实例变量将此算法提取到自己的类中会增加可读性.由于算法非常具体,可能对其他类没用,因此将算法放入内部类中.因此,您可以避免使用仅由该算法使用的实例变量来混乱外部类. 有关: > Why/when should you use nested classes in .net? Or shouldn’t you? (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |