日期:2014-05-19  浏览次数:21014 次

c# 实例化一个form?
为什么不能直接用form2.Show();

而是先要form2   f2   =   new   form2();

----------------------------------------------------

类的静态构造函数有什么用?

要设定类的字段初始值,直接设定不就行了?

------解决方案--------------------
太有难度,思考中...
------解决方案--------------------
1、静态构造函数和实例构造函数可共存:前者为类加载时执行,后者为new时执行
2、静态构造函数无参数,且访问修饰符存在与否没意义:由.NET运行库调用
3、静态构造函数使用的原因:在第一次使用类时,从外部源中初始化某些静态字段方法
4、静态构造函数的执行:.NET运行库不能确保其执行时间,但必定是在代码引用类前执行,且仅仅只一次

------解决方案--------------------
form2是类,而Show方法是对象的方法,并不是类的方法,从类form2实力化得到对象f2,就可以用Show方法了,而有些方法是类方法(又称静态方法),类无须实力化就可以使用的,所有的构造函数在使用时机上可以理解为静态方法,所以存在这样的写法:new form(2);,在c#语法中,一般静态方法在定义时必须使用关键字static,在静态方法内部不允许使用关键字this,但构造函数除外。在net框架中存在了大量的方便易用的类静态方法。

------解决方案--------------------
类的构造函数有什么用?用途确实越来越小了,普通字段的初始化可以在定义时直接设定,而复杂字段可以用属性包装,并采用惰性创建。而比较明显的一个用途是,有些字段或属性的初始化是在对象创建时传入的,如果数量比较多的话,采用一批多态构造函数,以方便调用者创建使用。

------解决方案--------------------

------解决方案--------------------
窗体只实例化一次完整 示例


//一. 基类

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class FormBase : Form
{
private static bool isClose;

public FormBase()
{
InitializeComponent();
isClose = false;
}

public bool IsClose
{
get { return isClose; }
}

private void FormBase_FormClosed(object sender, FormClosedEventArgs e)
{
isClose = true;
}
}
}

//二. 被调用子窗体
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form2 : FormBase
{
private static Form2 f2;

private Form2()
{
InitializeComponent();
}

private Form2(Form1 f1):base()
{
InitializeComponent();
}

public static Form2 GetF2(Form1 f1)
{
if (f2 == null)
{
f2 = new Form2(f1);
}

return f2;
}

private void Form2_FormClosed(object sender, FormClosedEventArgs e)
{
f2 = null;
}
}
}

//三. 主窗体
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form1 : FormBase
{
private FormBase f2;

public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{