2008年10月10日星期五

VS设计时问题

下面类似的错误,一般是由于自定义控件中出现。

The variable '****' is either undeclared or was never assigned.

Hide    Edit

at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.Error(IDesignerSerializationManager manager, String exceptionText, String helpLink)
at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeExpression(IDesignerSerializationManager manager, String name, CodeExpression expression)
at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializePropertyAssignStatement(IDesignerSerializationManager manager, CodeAssignStatement statement, CodePropertyReferenceExpression propertyReferenceEx, Boolean reportError)
at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeAssignStatement(IDesignerSerializationManager manager, CodeAssignStatement statement)
at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeStatement(IDesignerSerializationManager manager, CodeStatement statement)

VS应该是(猜测?)通过InitializeComponent函数来初始化在设计时相关的变量,所以程序本身运行时不会有问题,不过却无法正常的显示设计的页面。
例如下面的代码(部分)
      ///
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        ///

        private void InitializeComponent()
        {
           
            this.SuspendLayout();
            //
            // button1
            //
            this.button1.Location = new System.Drawing.Point(40, 86);
        
            ……
            this.ResumeLayout(false);

        }

        #endregion
      
        private System.Windows.Forms.Button button1= new System.Windows.Forms.Button();


button1变量在InitializeComponent函数外声明并初始化,虽然不会影响程序的正确性,不过再设计时无法确认button1是否初始化
因此,会给出错误(原则上说VS在这点上有点苛刻。),改为下面的可以消除设计时的错误。
private void InitializeComponent()
        {
            button1 = new System.Windows.Forms.Button();
            this.SuspendLayout();
            //
            // button1
            //
            this.button1.Location = new System.Drawing.Point(40, 86);
            ……
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.Button button1;//= new System.Windows.Forms.Button();

上面的错误的话,VS2008中还可以给出错误的行数(2005不可以),可以据此修改,不过下面一种可以引起的错误,VS2008
也没法给出。
比如我在自定义控件里定义一个属性(Property)
public string JustForTest
        {
            get
            {
                return ConfigurationManager.AppSettings["Test"]??string.Empty;
            }
            set
            {
                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                config.AppSettings.Settings["Test"].Value = value;
                config.Save(ConfigurationSaveMode.Modified);
            }
        }

    这样的属性在运行时和设计时对这个控件来说也是没有问题的,不过在设计的时候,比如我把这个自定义的控件添加到了一个Form上,
这个Form就会出现问题。
VS会自动的初始化这个控件的Public属性值,
 this.userControl11.JustForTest = null;
而在设计时,这个属性是无法获取的,错误产生。

VS还需要继续在设计时的支持方面努力啊

没有评论: