⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 sample2.cs

📁 C#函数手册
💻 CS
字号:
namespace apiBook
{
	using System;
	using System.IO;
	using System.Data;
	public class TestConstraintClass 
	{
		public static void Main()
		{
			TestConstraintClass test=new TestConstraintClass();
			DataTable testDT=new DataTable("student");
			DataColumn testDC;			
			testDC = new DataColumn();
			testDC.DataType = Type.GetType("System.Int32");				   testDC.ColumnName="Id";
			testDT.Columns.Add(testDC);
			testDC = new DataColumn();
			testDC.DataType = Type.GetType("System.Int32");			         testDC.ColumnName="sId";
			testDT.Columns.Add(testDC);
			testDC = new DataColumn();
			testDC.DataType = Type.GetType("System.String");
			testDC.ColumnName = "Name";	
			testDC.Unique=true;
			testDT.Columns.Add(testDC);
			Console.WriteLine("表名:" + testDT.TableName);
			Console.WriteLine("表初始约束信息:");
			test.DoPrint(testDT);
			Console.WriteLine();
			Console.WriteLine("在Id列添加一个约束主键:");
			testDT.Constraints.Add("idUniqueConstraint",testDT.Columns["Id"],true);
			//使用Add方法添加主键
			test.DoPrint(testDT);
			Console.WriteLine();
			Console.WriteLine("把sId列作为Id列的外键:");
			testDT.Constraints.Add("ForeignKey",
				testDT.Columns["Id"],testDT.Columns["sId"]);
			//使用Add方法添加外键
			test.DoPrint(testDT);	
			try
			{
				Constraint c =testDT.Constraints[0];
				Console.WriteLine("第一个约束能否被移除?" + testDT.Constraints.CanRemove(c));
				//使用CanRemove方法判断该约束能否被移除
			}
			catch(Exception e)
			{
				Console.WriteLine(e.ToString());
			}
			Console.WriteLine("是否有名为ForeignKey的约束?"+testDT.Constraints.Contains("ForeignKey"));
			//使用Contains方法判断是否有名为ForeignKey的约束
			Console.WriteLine("名为ForeignKey约束的索引:"+testDT.Constraints.IndexOf("ForeignKey"));
			//使用IndexOf方法获取名为ForeignKey约束的索引信息Console.WriteLine();
			testDT.Constraints.Remove("Constraint1");
			//使用Remove方法移除名为Constraint1的约束
			Console.WriteLine("移除名为Constraint1约束后:");
			test.DoPrint(testDT);
			Console.WriteLine();
			Console.WriteLine("移除第2约束后:");
			testDT.Constraints.RemoveAt(1);
			//使用RemoveAt方法移除指定索引位置的约束
			test.DoPrint(testDT);
			Console.WriteLine("清除所有约束后:");
			testDT.Constraints.Clear();
			//使用Clear方法清楚集合中的所有约束
			test.DoPrint(testDT);
			Console.ReadLine();
		}
		public void DoPrint(DataTable dt)
		{
			foreach(Constraint testC in dt.Constraints ) 
			{					
				Console.WriteLine("约束信息: " + testC.ToString());
				Console.WriteLine("约束类型: " + testC.GetType().ToString());
			}
		}
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -