技术点滴
几年前零零散散在 cnblogs 发布的文字,现在将它们全删除了,整合为一篇文章,记录下来,以备有时重读。
实现IEnumerator接口
using System;
using System.Collections;
public class Person
{
public Person(string fName, string lName)
{
this.firstName = fName;
this.lastName = lName;
}
public string firstName;
public string lastName;
}
public class People : IEnumerable
{
private Person[] _people;
public People(Person[] pArray)
{
_people = new Person[pArray.Length];
for (int i = 0; i < pArray.Length; i++)
{
_people[i] = pArray[i];
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return (IEnumerator) GetEnumerator();
}
public PeopleEnum GetEnumerator()
{
return new PeopleEnum(_people);
}
}
public class PeopleEnum : IEnumerator
{
public Person[] _people;
// Enumerators are positioned before the first element
// until the first MoveNext() call.
int position = -1;
public PeopleEnum(Person[] list)
{
_people = list;
}
public bool MoveNext()
{
position++;
return (position < _people.Length);
}
public void Reset()
{
position = -1;
}
object IEnumerator.Current
{
get
{
return Current;
}
}
public Person Current
{
get
{
try
{
return _people[position];
}
catch (IndexOutOfRangeException)
{
throw new InvalidOperationException();
}
}
}
}
class App
{
static void Main()
{
Person[] peopleArray = new Person[3]
{
new Person("John", "Smith"),
new Person("Jim", "Johnson"),
new Person("Sue", "Rabon"),
};
People peopleList = new People(peopleArray);
foreach (Person p in peopleList)
Console.WriteLine(p.firstName + " " + p.lastName);
}
}
/* This code produces output similar to the following:
*
* John Smith
* Jim Johnson
* Sue Rabon
*
*/
GetEnumerator 方法的使用
下面的代码示例演示如何使用 GetEnumerator 方法来创建 System.Collections.IEnumerator 接口,该接口可被循环访问以显示 DataGridColumnCollection 集合的内容。
view plaincopy to clipboardprint?
<%@ Page Language="C#" AutoEventWireup="True" %>
<%@ Import Namespace="System.Data" %>
<HTML>
<SCRIPT language=C# runat="server">
ICollection CreateDataSource()
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add(new DataColumn("IntegerValue", typeof(Int32)));
dt.Columns.Add(new DataColumn("StringValue", typeof(string)));
dt.Columns.Add(new DataColumn("CurrencyValue", typeof(double)));
for (int i = 0; i < 9; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = "Item " + i.ToString();
dr[2] = 1.23 * (i + 1);
dt.Rows.Add(dr);
}
DataView dv = new DataView(dt);
return dv;
}
void Page_Load(Object sender, EventArgs e)
{
if (!IsPostBack)
{
// Load this data only once.
ItemsGrid.DataSource= CreateDataSource();
ItemsGrid.DataBind();
}
}
void Button_Click(Object sender, EventArgs e)
{
// Create IEnumerator for rows.
IEnumerator myEnum = ItemsGrid.Columns.GetEnumerator();
DataGridColumn column;
Label1.Text = "The header text of the items in the IEnumerator are: <br><br>";
// Iterate through IEnumerator and display its contents.
while (myEnum.MoveNext())
{
column = (DataGridColumn)myEnum.Current;
Label1.Text += column.HeaderText + "<br>";
}
}
</SCRIPT>
<FORM runat="server">
<H3>DataGridColumnCollection GetEnumerator Example</H3>
<B>Product List</B>
<ASP:DATAGRID id=ItemsGrid runat="server" AutoGenerateColumns="false" CellPadding="3" BorderWidth="1" BorderColor="black">
<HEADERSTYLE BackColor="#00aaaa">
</HEADERSTYLE>
<COLUMNS>
<ASP:BOUNDCOLUMN DataField="IntegerValue" HeaderText="Item Number" />
<ASP:BOUNDCOLUMN DataField="StringValue" HeaderText="Item" />
<ASP:BOUNDCOLUMN DataField="CurrencyValue" HeaderText="Price" DataFormatString="{0:c}">
<ITEMSTYLE HorizontalAlign="right">
</ITEMSTYLE>
</ASP:BOUNDCOLUMN>
</COLUMNS>
</ASP:DATAGRID>
<P>
<ASP:BUTTON id=Button1 onclick=Button_Click runat="server" Text="Create IEnumerator" />
<P>
<ASP:LABEL id=Label1 runat="server" />
</FORM>
匿名变量与隐式类型变量
匿名变量与隐式类型变量的区别 l、隐式类型变量是指我们可以通过等号右边的表达式,推断出等号左边该是那种类型。如: var Name = "C#"; 我们可以根据等号右边的表达式“C#”,推断出等号左边的变量Name是string类型。 2、 匿名变量则是指根据这个类型的初始化函数,我们可以推导出和创建出这个类型的实例。这两个特性很多时候是一起作用的。如: var book = new { Name = "C#", Price = 100}; 上面的book就是一个匿名变量。其中的Name = "C#"和Price = 100又可以分别看作是隐式类型变量。
CliPBoard
System.Windows.Forms.CliPBoard
Clipboard.SetDataObject(this.textBox1.Text,true);
程序使用的一些类或方法:
IDataObject接口,为数据提供与格式无关的机制,也就是说使用该对象可以存储的数据不受格式的限制,因为我们预先并不知道剪贴板中的数据是什么格式的
使用Clipboard类的GetDataObject()方法得到剪贴板中的数据,该方法返回一个IDataObject
使用IDataObject对象的GetDataPresent(System.Type format)判断IDataObject对象中存储的数据是否可以转换为指定的格式,该方法接收一个参数该参数必须是系统预定义的一种格式类型,该方法返回bool值
最后使用IDataObject对象的GetData(System.Type format)方法得到数据内容,该方法返回Object使用前要进行类型转换
具体代码如下:
private void button1_Click(object sender, System.EventArgs e)
{
// GetDataObject检索当前剪贴板上的数据
IDataObject iData =
Clipboard.GetDataObject();
// 将数据与指定的格式进行匹配,返回bool
if
(iData.GetDataPresent(DataFormats.Text))
{
// GetData检索数据并指定一个格式
this.label1.Text = (string)iData.GetData(DataFormats.Text);
}
else
{
MessageBox.Show("目前剪贴板中数据不可转换为文本","错误");
}
}
private void button2_Click(object sender, System.EventArgs e)
{
IDataObject iData = Clipboard.GetDataObject();
if
(iData.GetDataPresent(DataFormats.Bitmap))
{
this.pictureBox1.SizeMode
= PictureBoxSizeMode.StretchImage;
this.pictureBox1.Image
= (Bitmap)iData.GetData(DataFormats.Bitmap);
}
else
{
MessageBox.Show("目前剪贴板中数据不可转换为图片","错误");
}
}
private void button3_Click(object sender, System.EventArgs e)
{
Close();
}
有关XML
XMLRoot.SelectSingleNode("EntityName")
应该可以选到这个节点吧,折腾半天就是选不到,原来是根节点使用了定制的命名空间属性
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(Server.MapPath("wadl.xml"));
XmlElement root = xmlDoc.DocumentElement;
string nameSpace = root.NamespaceURI;
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
nsmgr.AddNamespace("", nameSpace);
XmlNode rectifyele =
xmlDoc.SelectSingleNode(@"application/resources", nsmgr);
把你的后两行改一下
C# code
nsmgr.AddNamespace("ya", nameSpace);
XmlNode rectifyele = xmlDoc.SelectSingleNode(@"//ya:resources",
nsmgr);
XmlNode xn=xmlDoc.SelectSingleNode("bookstore");
已知有一个XML文件(bookstore.xml)如下:
<?xml version="1.0" encoding="gb2312"?>
<bookstore>
<book genre="fantasy" ISBN="2-3631-4">
<title>Oberon's Legacy</title>
<author>Corets, Eva</author>
<price>5.95</price>
</book>
</bookstore>
1、往<bookstore>节点中插入一个<book>节点:
XmlDocument xmlDoc=new XmlDocument();
xmlDoc.Load("bookstore.xml");
XmlNode root=xmlDoc.SelectSingleNode("bookstore");//查找<bookstore>
XmlElement xe1=xmlDoc.CreateElement("book");//创建一个<book>节点
xe1.SetAttribute("genre","李赞红");//设置该节点genre属性
xe1.SetAttribute("ISBN","2-3631-4");//设置该节点ISBN属性
XmlElement xesub1=xmlDoc.CreateElement("title");
xesub1.InnerText="CS从入门到精通";//设置文本节点
xe1.AppendChild(xesub1);//添加到<book>节点中
XmlElement xesub2=xmlDoc.CreateElement("author");
xesub2.InnerText="候捷";
xe1.AppendChild(xesub2);
XmlElement xesub3=xmlDoc.CreateElement("price");
xesub3.InnerText="58.3";
xe1.AppendChild(xesub3);
root.AppendChild(xe1);//添加到<bookstore>节点中
xmlDoc.Save("bookstore.xml");
//===============================================
结果为:
<?xml version="1.0" encoding="gb2312"?>
<bookstore>
<book genre="fantasy" ISBN="2-3631-4">
<title>Oberon's Legacy</title>
<author>Corets, Eva</author>
<price>5.95</price>
</book>
<book genre="李赞红"
ISBN="2-3631-4">
<title>CS从入门到精通</title>
<author>候捷</author>
<price>58.3</price>
</book>
</bookstore>
2、修改节点:将genre属性值为“李赞红“的节点的genre值改为“update李赞红”,将该节点的子节点<author>的文本修改为“亚胜”。
XmlNodeList
nodeList=xmlDoc.SelectSingleNode("bookstore").ChildNodes;//获取bookstore节点的所有子节点
foreach(XmlNode xn in nodeList)//遍历所有子节点
{
XmlElement xe=(XmlElement)xn;//将子节点类型转换为XmlElement类型
if(xe.GetAttribute("genre")=="李赞红")//如果genre属性值为“李赞红”
{
xe.SetAttribute("genre","update李赞红");//则修改该属性为“update李赞红”
XmlNodeList nls=xe.ChildNodes;//继续获取xe子节点的所有子节点
foreach(XmlNode xn1 in nls)//遍历
{
XmlElement xe2=(XmlElement)xn1;//转换类型
if(xe2.Name=="author")//如果找到
{
xe2.InnerText="亚胜";//则修改
break;//找到退出来就可以了
}
}
break;
}
}
xmlDoc.Save("bookstore.xml");//保存。
//==================================================
最后结果为:
<?xml version="1.0" encoding="gb2312"?>
<bookstore>
<book genre="fantasy" ISBN="2-3631-4">
<title>Oberon's Legacy</title>
<author>Corets, Eva</author>
<price>5.95</price>
</book>
<book genre="update李赞红"
ISBN="2-3631-4">
<title>CS从入门到精通</title>
<author>亚胜</author>
<price>58.3</price>
</book>
</bookstore>
3、删除 <book genre="fantasy"
ISBN="2-3631-4">节点的genre属性,删除 <book genre="update李赞红"
ISBN="2-3631-4">节点。
XmlNodeList xnl=xmlDoc.SelectSingleNode("bookstore").ChildNodes;
foreach(XmlNode xn in xnl)
{
XmlElement xe=(XmlElement)xn;
if(xe.GetAttribute("genre")=="fantasy")
{
xe.RemoveAttribute("genre");//删除genre属性
}
else if(xe.GetAttribute("genre")=="update李赞红")
{
xe.RemoveAll();//删除该节点的全部内容
}
}
xmlDoc.Save("bookstore.xml");
//===========================================
最后结果为:
<?xml version="1.0" encoding="gb2312"?>
<bookstore>
<book ISBN="2-3631-4">
<title>Oberon's Legacy</title>
<author>Corets, Eva</author>
<price>5.95</price>
</book>
<book>
</book>
</bookstore>
4、显示所有数据。
XmlNode xn=xmlDoc.SelectSingleNode("bookstore");
XmlNodeList xnl=xn.ChildNodes;
foreach(XmlNode xnf in xnl)
{
XmlElement xe=(XmlElement)xnf;
Console.WriteLine(xe.GetAttribute("genre"));//显示属性值
Console.WriteLine(xe.GetAttribute("ISBN"));
XmlNodeList xnf1=xe.ChildNodes;
foreach(XmlNode xn2 in xnf1)
{
Console.WriteLine(xn2.InnerText);//显示子节点点文本
}
}
使用 CreateElement 创建Xml节点时,必须指定与根节点相同的命名空间,新建节点才不会显示 xmlns=" " 或 xmlns="......"
增、 删 、改 Xml 节点后,文件无法保存,总说“别的进程打开”,整死我喽,怎么检查代码都没问题,终于想到检查XML文档是否是只读的,唉,文档也不是只读的,时间一分一 秒过去,几小时了,咅题还是没有得到解决,心情都搞烦了。最后想到它的父或祖先文件夹会否是只读的,坑爹啊,根文件夹只读......
杯具了,搞了半天,原来:为了不读出注释节点,用了XmlReader,就这玩意儿打开后没关.
XmlDocument XmlDoc = new XmlDocument();
XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreComments = true;
XmlReader reader = XmlReader.Create(XmlFileFullName, settings);
XmlDoc.Load(reader);
reader.Close();
就象上次搞Excel文档的应用,定制的扫描方法打开文档后, 我知道关掉,而用SQL方式打开后,就没关,结果也是一会儿正常 ,一会儿不正常 ,整死人了。以后注意了,凡是数据库操作、文件流操作, 一定注意相关流、连接关了没有。
编码心得
用SQL server 2000的企业管理器是无法连SQL 2008,但用SQL server 2000的查询分析器是可以连上SQL 2008的。
第一次接触到完全以代码的对齐方式,代替大花括号界定代码块的语言:Python.
不管是在哪个平台环境(.NET,Java,PHP等),如果遇上百思不得其解的怪问题,调试无法通过,首先想想是否缓存在作怪吧。被这鬼东西打击n多次了:清空缓存或删除缓存文件后按新版本重新生成,或许就解了问题。
C#不同版本 委托的变化写法
public delegate void getString_Handler(string
s);
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
void getString_Handler_Implement(string s)
{
MessageBox.Show(s);
}
protected void Test_Delegate()
{
getString_Handler get1 = new getString_Handler(getString_Handler_Implement);//最老C#版 本定义委托方式
getString_Handler get2=new getString_Handler(
delegate(string s)
{
MessageBox.Show(s);
}
);
getString_Handler get3 = x => MessageBox.Show(x);
get1("Hello get1 ");
get2("Hello get2 ");
get3("Hello get3 ");
}
private void button1_Click(object sender, EventArgs e)
{
Test_Delegate();
}
}TestDelegate(string s);
ToolStripMenuItem miNewMode = new ToolStripMenuItem();
miNewMode.Name = "mi" + key;
//this.miNewMode.Size = new
System.Drawing.Size(174, 22);
miNewMode.Text = key;
miNewMode.Tag = syntaxModes[key];
miNewMode.Click += new System.EventHandler(
delegate(object sender, EventArgs e)
{
ToolStripMenuItem miThis = sender as
ToolStripMenuItem;
if (miThis != null &&
miThis.Tag != null)
{
ToolStripDropDownMenu owner =
miThis.Owner as ToolStripDropDownMenu;
if (owner != null &&
owner.Items.Count > 0)
{
foreach
(ToolStripMenuItem mi in owner.Items)
{
mi.Checked = false;
}
miThis.Checked = true;
}
if (ActiveEditor != null)
{
ActiveEditor.Document.HighlightingStrategy
= HighlightingStrategyFactory.CreateHighlightingStrategy(miThis.Tag as string);
}
}
});
数据源绑定到DataGridView时,格式化Cell显示文本
利用dataGridView1的CellFormatting事件
该事件在单元格显示数据库前触发,有很高的执行效率,不会影响速度
private void dataGridView1_CellFormatting(object sender,
DataGridViewCellFormattingEventArgs e)
{
foreach (DataGridViewRow dr in dataGridView1.Rows)
{
switch (dr.Cells[2].Value.ToString)
{
case "1":
dr.Cells[2].Value = "一";
break;
case "2":
dr.Cells[2].Value = "二";
break;
case "3":
dr.Cells[2].Value = "三";
break;
case "4":
dr.Cells[2].Value = "四";
break;
//........
}
}
}
普通文本框编辑格式文本(比如IronPathon代码)
普通文本框编辑语言代码后保存,会将 "\r\n" 替换为 "\n",你重新在文本框中显示代码,给你展成“一维”的了,不会换行。你要将"\r\n"再替换回"\r\n",才能按正常的语法格式显示。汗!
C#嵌入IronPython脚本示例(hello world)
最简单的hello world程序。
首先,我们必须有一个IronPython脚本引擎库(IronPython.dll),我用的版本是V1.0,你可以在网上直接下到相关源码,编译后即生成IronPython.dll。
新建一个C#桌面程序,引用该库后,我们便开始编写第一个程序。
下面是C#中的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using IronPython.Hosting;
namespace TestIronPython
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object
sender, EventArgs e)
{
PythonEngine
scriptEngine = new PythonEngine();
scriptEngine.Execute(textBox1.Text);
}
}
}
代码很简单,声明了一个scriptEngine 实例,直接用Execute执行代码即可。下面看看py的代码该怎么写:
import clr
clr.AddReferenceByPartialName("System.Windows.Forms")
clr.AddReferenceByPartialName("System.Drawing")
from System.Windows.Forms import *
from System.Drawing import *
MessageBox.Show("Hello World!")
第一句代码很重要,导入.net clr,用clr的AddReferenceByPartialName方法加载我们熟悉的System.Windows.Forms和System.Drawing库,最后可以直接执行.net中的MessageBox方法。
运行后,直接单击button1,即可弹出一个对话框"Hello World!"

浙公网安备 33010602011771号