Chinaunix首页 | 论坛 | 博客
  • 博客访问: 12525972
  • 博文数量: 1293
  • 博客积分: 13501
  • 博客等级: 上将
  • 技术积分: 17974
  • 用 户 组: 普通用户
  • 注册时间: 2011-03-08 18:11
文章分类

全部博文(1293)

文章存档

2019年(1)

2018年(1)

2016年(118)

2015年(257)

2014年(128)

2013年(222)

2012年(229)

2011年(337)

分类: 嵌入式

2012-09-20 11:37:41

1、案例出错现场“无法通过嵌套类型访问外部类型的非静态成员”


image_thumb17 image_thumb18 image_thumb19


 

2、源文件代码分析


点击(此处)折叠或打开

  1. 基本类文件结构如下:

  2. xxxxx.cs

  3. using ……;

  4. namespace AAA

  5. {

  6. ……

  7. public partial class BBB

  8. {

  9.       public void CWaitForGetPresetOver()

  10. {

  11. //////

  12. }

  13. public setProgressBar()

  14. {

  15. //////////

  16. }


  17. ////////////////////////////////////////////////////////////////////////////////////////

  18. // CWaitForGetPresetOver类结构

  19. public class CWaitForGetPresetOver
  20. {

  21. public CWaitForGetPresetOver()

  22. {

  23. //////////////

  24. }

  25. public void WaitForGetPresetOver()

  26. {
  27. setProgressBar();

  28. }

  29. }

  30. /////////////////////////////////////////////////////////////////////////////////////////

  31. // BBB中某些函数对CWaitForGetPresetOver的调用
  32. ...........

  33. CWaitForGetPresetOver CWForGetPresetOver_demo = new CWaitForGetPresetOver();
  34. CWForGetPresetOver_demo.CWaitForGetPresetOver();
  35. ...........

  36. }

  37. }

上面CS文件的基本结构是:

外部类型 BBB,

BBB有一个公有方法,setProgressBar();

BBB里面有一个内部类型CWaitForGetPresetOver;

上面代码,当执行到CWForGetPresetOver_demo.CWaitForGetPresetOver();的时候就会爆出1中的错误。

 

3、解决方法


主要是修改嵌套类型,在其构造函数中将外部类型传进去;再在嵌套类型内部通过外部类型对象进行操作其成员函数!

代码修改如下:

点击(此处)折叠或打开

  1. //  嵌套类型构造函数
  2. public class CWaitForGetPresetOver
  3. {

  4. BBB BBB_demo;



  5. // 嵌套类型构造函数中传入外部类型

  6. public CWaitForGetPresetOver(BBB BBB_demo)

  7. {

  8. this.BBB BBB_demo = BBB BBB_demo;

  9. }



  10. public void WaitForGetPresetOver()

  11. {

  12. //通过传进来外部类型,调用其对象成员

  13. BBB_demo.setProgressBar();

  14. }


4、参考文献

Msdn上说:
嵌套类型(或内部类型)可访问包含类型(或外部类型)。若要访问包含类型,请将其作为构造函数传递给嵌套类型。例如:


点击(此处)折叠或打开

  1. C# code
  2. public class Container
  3. {
  4.     public class Nested
  5.     {
  6.         private Container m_parent;

  7.         public Nested()
  8.         {
  9.         }
  10.         public Nested(Container parent)
  11.         {
  12.             m_parent = parent;
  13.         }
  14.     }
  15. }

据此,你的代码更改如下:
C# code


点击(此处)折叠或打开

  1. public class checkFlowThread
  2.         {
  3.             Form1 form1;
  4.             public checkFlowThread(Form1 f)
  5.             {
  6.                this.form1=f;
  7.             }
  8.             public void checkFlow()
  9.             {
  10.             form1.Label.Text = "想访问外部类的非静态成员";
  11.             }
  12.         }

嵌套类型可访问包含类型的私有成员和受保护的成员(包括所有继承的保护的成员)。 

阅读(6878) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~