C#泛型类创建与使用的方法

2016-01-25 02:05:09 365体育投注网址

本文实例为大家分享了C#泛型类创建与使用的具体代码,供大家参考,具体内容如下using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace ConsoleApplication13{ class Program { static void Main(string[] args) { Test<string,int> t = new Test<string,int>("Age",16); t.Run(); t.SetT1Value = "Height"; t.SetT2Value = 1000; t.Run(); Console.ReadKey(); } } class Test<T1,T2> { private T1 _t1; private T2 _t2; public Test(T1 v1,T2 v2) { _t1 = v1; _t2 = v2; } public T1 SetT1Value { set { _t1 = value; } } public T2 SetT2Value { set { _t2 = value; } } public void Run() { Console.WriteLine("The type of T1 is {0},the value is {1}",_t1.GetType().ToString(),_t1); Console.WriteLine("The type of T2 is{0},the value is {1}", _t2.GetType().ToString(), _t2); } }}运行结果:以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

公司的项目,通过json传回来的是这么个东西:NewsId":"94f52614-8764-46d7-a5fe-d0da1fe878ed","NewsTitle":"大型公选课《可持续发展与未来》系列二之现代经济(绿色经济)开始网上选课报名","NewsContent":"<span style="font-size:12pt;font-family:宋体;color:black;line-height:150%;"><span>近日,伴随着我校郑时龄院士、童小华教授分别在四平、嘉定举行的精彩演讲,本学期我校着力打造的大型公共选修课程《可持续发展与未来》之系列一已经圆满结束。该课程也是我校</span>“<span>可持续发展辅修专业</span>”<span>的核心必修课程之一。</span></span> <p style="text-indent:21pt;"></p>.........</span>各种查询之后发现无法解析的根本原因就是里面有双引号" " "和反斜杠" \ ".还不能直接对json进行转义,否则会将json本身自带的双引号都给转义了,所以不能暴力转义上网找的方法://将坏的json数据里面的双引号,改为中文的双引号(啥都行,只要不是双引号就行) public String jsonStringConvert(String s){ char[] temp = s.toCharArray(); int n = temp.length; for(int i =0;i<n;i++){ if(temp[i]==':'&&temp[i+1]=='"'){ for(int j =i+2;j<n;j++){ if(temp[j]=='"'){ if(temp[j+1]!=',' && temp[j+1]!='}'){ temp[j]='”'; }else if(temp[j+1]==',' || temp[j+1]=='}'){ break ; } } } } } return new String(temp); }</span>此方法能将json本身的双引号以外的双引号转义为中文的双引号(其他什么都行)。这样就能够转义为正确的json字符串。备忘:在此方法之前,还要将html代码去空格,否则json也不能够解析,去空格方法:public String replaceBlank(String str) { String dest = ""; if (str != null) { Pattern p = Pattern.compile("\\s*|\t|\r|\n"); Matcher m = p.matcher(str); dest = m.replaceAll(""); // Pattern p2 = Pattern.compile("\\s*\""); // Matcher m2 = p2.matcher(dest); // dest = m2.replaceAll("\'"); dest = dest.replace("=\"", "='"); p = Pattern.compile("\"\0*>"); m = p.matcher(dest); dest = m.replaceAll(">'"); } return dest;}</span>以上这篇解析错误富文本json字符串(带双引号)的快速解决方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

本文实例汇总了C#中@的用法,对C#程序设计来说有不错的借鉴价值。具体如下:一 字符串中的用法1.学过C#的人都知道C# 中字符串常量可以以@ 开头声名,这样的优点是转义序列“不”被处理,按“原样”输出,即我们不需要对转义字符加上 \ (反斜扛),就可以轻松coding。如,string filePath = @"c:\Docs\Source\a.txt" // rather than "c:\\Docs\\Source\\a.txt" 2.如要在一个用 @ 引起来的字符串中包括一个双引号,就需要使用两对双引号了。这时候你不能使用 \ 来转义爽引号了,因为在这里 \ 的转义用途已经被 @  “屏蔽”掉了。如,@"""Ahoy!"" cried the captain." // 输出为: "Ahoy!" cried the captain. 这有点像SQL中的单引号常量处理方式:DECLARE @msg varchar(100) SET @msg = ''Ahoy!'' cried the captain.' -- 输出为: 'Ahoy!' cried the captain. [email protected]会识别换行符其实这个特性,我不知道怎么描述,只是偶然发现的,先来看看下面的代码:string script = @" <script type=""type/javascript""> function doSomething() { } </script>"; 这段代码在cs文件中写js,结构就很清晰了,正常情况我们是这样coding的:string script2 = "<script type=\"type/javascript\">function doSomething(){}</script>"; 或者:string script3 = "<script type=\"type/javascript\">" + "function doSomething(){ " + "}</script>"; 通常我们会选择后者,因为js代码一般比较长,或者方法体很大,或者需要连接其他变量,这样结构比较清晰。注意:如果“拼接”的次数很多,应该考虑使用StringBuilder了,有助于提高性能。还有一种场景,也很常见,在程序中拼接 SQL 语句,如private const string SQL_INS_USER = @" INSERT INTO t_User([UserName], [Password], Email) VALUES(@UserName, @Password, @Email)"; 这样就像写存储过程一般,保持相当高的代码清晰度。然而,我们需要关注一个问题:字符串长度看下面的测试代码:private const string SQL_INS_USER1 = @" INSERT INTO t_User([UserName], [Password], Email) VALUES(@UserName, @Password, @Email)"; private const string SQL_INS_USER2 = @"INSERT INTO t_User([UserName], [Password], Email) VALUES(@UserName, @Password, @Email)"; private const string SQL_INS_USER3 = @"INSERT INTO t_User([UserName], [Password], Email) VALUES(@UserName, @Password, @Email)"; static void Main(string[] args) { Console.WriteLine(SQL_INS_USER1.Length); // 126 Console.WriteLine(SQL_INS_USER2.Length); // 112 Console.WriteLine(SQL_INS_USER3.Length); // 86 } 这里可以看到三个字符串长度分别相差了,14=126-112和26=112-86,注意观察了,在代码编辑器中,SQL_INS_USER1 中第一个换行符号之后,我缩进13个空格(INSERT之前),而SQL_INS_USER2 中第一个换行符号之后,我缩进25个空格(VALUES之前),那么,加上一个换行符,刚刚好 14和26如此编写代码,虽然提高了代码的清晰度和简便性,却无行中带来了另一个问题:字符长度!很多场景下我们希望字符串越短越好,如,通过ADO.NET 发送 SQL 语句给数据库执行。所以还是慎用之!二 标识符中的用法在 C#  规范中, @  可以作为标识符(类名、变量名、方法名等)的第一个字符,以允许C# 中保留关键字作为自己定义的标识符。如下代码:class @class { public static void @static(bool @bool) { if (@bool) System.Console.WriteLine("true"); else System.Console.WriteLine("false"); } } class Class1 { static void M() { cl\u0061ss.st\u0061tic(true); } } 注意,@虽然出现在标识符中,但不作为标识符本身的一部分。因此,以上示例,定义了一个名为 class 的类,并包含一个名为 static 的方法,以及一个参数名为了 bool 的形参。这样,对于跨语言的移植带来了便利。因为,某个单词在 C#  中作为保留关键字,但是在其他语言中也许不是。

WPF换肤的设计原理,利用资源字典为每种皮肤资源添加不同的样式,在后台切换皮肤资源文件。截图上图中,第一张图采用规则样式,第二张图采用不规则样式,截图的时候略有瑕疵。资源字典规则样式资源Skin.RegularStyle.xaml<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <!--Window样式--> <Style x:Key="WindowStyle" TargetType="Window"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="Window"> <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> <Border.Background> <LinearGradientBrush StartPoint="0,0" EndPoint="0,1"> <GradientStop Color="Green" Offset="0"></GradientStop> <GradientStop Color="LightGreen" Offset="0.4"></GradientStop> <GradientStop Color="White" Offset="1"></GradientStop> </LinearGradientBrush> </Border.Background> <ContentPresenter></ContentPresenter> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> <!--Button样式--> <Style TargetType="Button"> <Setter Property="Width" Value="70"></Setter> <Setter Property="Height" Value="23"></Setter> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="Button"> <Border Name="bdr" Cursor="Arrow" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> <Border.Background> <LinearGradientBrush StartPoint="0,0" EndPoint="0,1"> <GradientStop Color="White" Offset="0"></GradientStop> <GradientStop Color="LightGreen" Offset="0.3"></GradientStop> <GradientStop Color="Green" Offset="1"></GradientStop> </LinearGradientBrush> </Border.Background> <TextBlock Name="tbk" Background="Transparent" Foreground="DarkGreen" TextAlignment="Center" Text="{TemplateBinding Content}"></TextBlock> </Border> <ControlTemplate.Triggers> <Trigger Property="IsMouseOver" Value="True"> <Setter TargetName="bdr" Property="Background"> <Setter.Value> <LinearGradientBrush StartPoint="0,0" EndPoint="0,1"> <GradientStop Color="LightGreen" Offset="0"></GradientStop> <GradientStop Color="Green" Offset="1"></GradientStop> </LinearGradientBrush> </Setter.Value> </Setter> <Setter TargetName="tbk" Property="Foreground" Value="White"></Setter> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> <!--TextBox样式--> <Style TargetType="TextBox"> <Setter Property="FontFamily" Value="SketchFlow Print"/> <Setter Property="FontSize" Value="14"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="TextBox"> <Border BorderBrush="DarkGreen" BorderThickness="0.5"> <ScrollViewer x:Name="PART_ContentHost" Focusable="false" HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Hidden"></ScrollViewer> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> <!--ContextMenu样式--> <Style TargetType="ContextMenu"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="ContextMenu"> <Border BorderBrush="Green" BorderThickness="1"> <ItemsPresenter/> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> <!--MenuItem样式--> <Style TargetType="MenuItem"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="MenuItem"> <Border Name="border" Background="LightGreen" BorderThickness="0"> <TextBlock Name="tbk" Background="Transparent" Padding="5,5" Text="{TemplateBinding Header}"></TextBlock> </Border> <ControlTemplate.Triggers> <Trigger Property="IsMouseOver" Value="True"> <Setter TargetName="border" Property="Background" Value="Green"></Setter> <Setter TargetName="tbk" Property="Foreground" Value="White"></Setter> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> <!--TextBlock样式--> <Style TargetType="TextBlock"> <Setter Property="FontFamily" Value="SketchFlow Print"/> <Setter Property="FontSize" Value="14"/> </Style></ResourceDictionary>不规则样式资源Skin.RoundedCornerStyle.xaml<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <!--Window样式--> <Style x:Key="WindowStyle" TargetType="Window"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="Window"> <Grid Margin="10"> <Rectangle Fill="{DynamicResource {x:Static SystemColors.WindowBrushKey}}" RadiusX="5" RadiusY="5"> <Rectangle.Effect> <DropShadowEffect BlurRadius="10" Color="Black" Direction="0" Opacity="0.8" RenderingBias="Performance" ShadowDepth="0"/> </Rectangle.Effect> </Rectangle> <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" SnapsToDevicePixels="True" CornerRadius="5"> <Border.Background> <LinearGradientBrush StartPoint="0,0" EndPoint="0,1"> <GradientStop Color="Blue" Offset="0"></GradientStop> <GradientStop Color="LightBlue" Offset="0.4"></GradientStop> <GradientStop Color="White" Offset="1"></GradientStop> </LinearGradientBrush> </Border.Background> <ContentPresenter></ContentPresenter> </Border> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style> <!--Button样式--> <Style TargetType="Button"> <Setter Property="Width" Value="70"></Setter> <Setter Property="Height" Value="23"></Setter> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="Button"> <Border Name="bdr" CornerRadius="5" Cursor="Hand" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> <TextBlock Name="tbk" Background="Transparent" Foreground="Yellow" TextAlignment="Center" Text="{Binding RelativeSource={RelativeSource TemplatedParent},Path=Content}"></TextBlock> <Border.Background> <LinearGradientBrush StartPoint="0,0" EndPoint="0,1"> <GradientStop Color="White" Offset="0"></GradientStop> <GradientStop Color="LightBlue" Offset="0.3"></GradientStop> <GradientStop Color="Blue" Offset="1"></GradientStop> </LinearGradientBrush> </Border.Background> </Border> <ControlTemplate.Triggers> <Trigger Property="IsMouseOver" Value="True"> <Setter TargetName="bdr" Property="Background"> <Setter.Value> <LinearGradientBrush StartPoint="0,0" EndPoint="0,1"> <GradientStop Color="LightBlue" Offset="0"></GradientStop> <GradientStop Color="Blue" Offset="1"></GradientStop> </LinearGradientBrush> </Setter.Value> </Setter> <Setter TargetName="tbk" Property="Foreground" Value="LightYellow"></Setter> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> <!--TextBox样式--> <Style TargetType="TextBox"> <Setter Property="FontFamily" Value="Times New Roman"></Setter> <Setter Property="FontSize" Value="14"></Setter> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="TextBox"> <Border BorderBrush="Blue" BorderThickness="0.5" CornerRadius="5"> <ScrollViewer x:Name="PART_ContentHost" Focusable="false" HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Hidden"></ScrollViewer> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> <!--ContextMenu样式--> <Style TargetType="ContextMenu"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="ContextMenu"> <Border CornerRadius="5" BorderBrush="Blue" BorderThickness="1"> <ItemsPresenter/> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> <!--MenuItem样式--> <Style TargetType="MenuItem"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="MenuItem"> <Border Name="border" Background="LightSkyBlue" BorderThickness="0" CornerRadius="5"> <TextBlock Name="tbk" Background="Transparent" Padding="5,5" Text="{TemplateBinding Header}"></TextBlock> </Border> <ControlTemplate.Triggers> <Trigger Property="IsMouseOver" Value="True"> <Setter TargetName="border" Property="Background" Value="BlueViolet"></Setter> <Setter TargetName="tbk" Property="Foreground" Value="White"></Setter> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> <!--TextBlock样式--> <Style TargetType="TextBlock"> <Setter Property="FontFamily" Value="Times New Roman"/> <Setter Property="FontSize" Value="14"/> </Style></ResourceDictionary>仔细观察上面定义的样式,你会发现在定义Window样式的时候指定了Key,其他的Control样式却没有指定Key。大家都知道,如果没有给Style指定Key,那么这个Style会应用到所有目标类型(TargetType)为指定类型的Control。请看下面一段文字:因为在换肤的过程中,需要动态加载Window的样式,所以用DynamicResource作绑定Style="{DynamicResource WindowStyle}"。App.xaml程序运行的时候,默认加载规则样式的皮肤。<Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="Dictionary\Skin.RegularStyle.xaml"></ResourceDictionary> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources>后台代码/// <summary> /// MenuItem的执行方法 /// </summary> /// <param name="parameter"></param> private void RelayMenuItemEvent(object parameter) { if (parameter.ToString() == RegularStyle) { ChangeSkinResource(Skins[0]); } else if (parameter.ToString() == RoundedCornerStyle) { ChangeSkinResource(Skins[1]); } } /// <summary> /// 更换皮肤资源 /// </summary> /// <param name="skin"></param> private void ChangeSkinResource(ResourceDictionary skin) { if (Application.Current.Resources.MergedDictionaries[0].Source.IsAbsoluteUri) { if (Application.Current.Resources.MergedDictionaries[0].Source.OriginalString != skin.Source.OriginalString) { Application.Current.Resources.MergedDictionaries[0] = skin; } } else { if (Application.Current.Resources.MergedDictionaries[0].Source.OriginalString.ToString('\\') != skin.Source.OriginalString.ToString('/')) { Application.Current.Resources.MergedDictionaries[0] = skin; } } }运行的时候在MainWindow上右键选择皮肤样式,就可以换肤了。源码下载:http://xiazai.jb51.net/201610/yuanma/WPFSkin(jb51.net).rar链接:stackoverflow以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

使用aspose.word 第三方的插件实现服务器端无需安装office组件导出word的功能#region 生成的excel文件命名和确保文件的唯一性 Random rd = new Random(); DateTime dtime = DateTime.Now; string Filename = "培训需求表" + dtime.Year.ToString() + dtime.Month.ToString() + dtime.Day.ToString() + dtime.Hour.ToString() + dtime.Minute.ToString() + dtime.Second.ToString() + Convert.ToString(rd.Next(99) * 97 + 100) + ".doc"; #endregion #region 定义变量 //建立Document物件,调用模块对word字体和table格式设置 string serverpath = Constants.GetAppSettingValue("LocalLogicPath") + Constants.GetAppSettingValue("LocalTemplate") + "px_xqjh_tx.doc"; Document doc = new Document(serverpath); //建立DocumentBuilder物件 DocumentBuilder builder = new DocumentBuilder(doc); #endregion #region 页面设置,设置页面为横向布局,设置纸张类型为A4纸或通过页面的宽度设置 //设置纸张布局 builder.PageSetup.PaperSize = PaperSize.A4; //builder.PageSetup.Orientation = Aspose.Words.Orientation.Landscape; #endregion #region 设置word全局的字体样式和字体大小 builder.RowFormat.Borders.LineStyle = LineStyle.Thick; builder.RowFormat.HeightRule = HeightRule.Auto; builder.RowFormat.Alignment = RowAlignment.Center; //builder.Font.Name = "仿宋-GB2312"; builder.Font.Name = "宋体"; builder.Font.Size = 10.5; //五号 #endregion List<double> widthList = new List<double>(); double remarkWidth = 0; for (int k = 0; k < 18; k++) { builder.MoveToCell(0, 1, k, 0); //移动单元格 double width = builder.CellFormat.Width;//获取单元格宽度 widthList.Add(width); remarkWidth += width; //Universal.ExceptionLog(k.ToString(), width.ToString()); } DataTable dtable = GetQuestionList(); if (dtable != null && dtable.Rows.Count > 0) { #region 绘制表格以及设置--------- 开头 doc.Range.Bookmarks["tbdw"].Text = this.lblcom.Text; builder.MoveToBookmark("pxtx"); //开始添加值 Aspose.Words.Tables.Table table = builder.StartTable(); builder.RowFormat.HeadingFormat = true; builder.ParagraphFormat.Alignment = ParagraphAlignment.Center; #endregion #region 数据集 for (int i = 0; i < dtable.Rows.Count; i++) { for (int j = 0; j < dtable.Columns.Count - 3; j++) { #region 列 builder.InsertCell();// 添加一个单元格 builder.CellFormat.Borders.LineStyle = LineStyle.Single; builder.CellFormat.Borders.Color = System.Drawing.Color.Black; builder.CellFormat.Shading.BackgroundPatternColor = System.Drawing.Color.FromArgb(255, 255, 255); builder.CellFormat.Width = widthList[j]; builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None; builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Top;//垂直居中对齐 builder.ParagraphFormat.Alignment = ParagraphAlignment.Left;//水平居中对齐 builder.Write(dtable.Rows[i][j].ToString().Trim()); //Universal.ExceptionLog((i + 1).ToString() + "*" + (j + 1).ToString(), dtable.Rows[i][j].ToString().Trim()); #endregion } builder.EndRow(); } #endregion #region 备注列 builder.InsertCell();// 添加一个单元格 builder.CellFormat.Borders.LineStyle = LineStyle.Single; builder.CellFormat.Borders.Color = System.Drawing.Color.Black; builder.CellFormat.Shading.BackgroundPatternColor = System.Drawing.Color.FromArgb(255, 255, 255); builder.CellFormat.Width = remarkWidth; builder.RowFormat.Height = 50; builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None; builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Top;//垂直居中对齐 builder.ParagraphFormat.Alignment = ParagraphAlignment.Left;//水平居中对齐 builder.Write("备注:"); builder.EndRow(); #endregion #region 绘制表格以及设置--------- 结尾 builder.EndTable(); doc.Range.Bookmarks["pxtx"].Text = ""; // 清掉标示 #endregion #region 计划编制和审批人 doc.Range.Bookmarks["writername"].Text = dtable.Rows[0]["reg_staff_name"].ToString(); doc.Range.Bookmarks["checkname"].Text = dtable.Rows[0]["check_man_name"].ToString(); #endregion } dtable.Dispose(); #region 保存数据. doc.Save(Filename, SaveFormat.Doc, SaveType.OpenInWord, Response); //保存为doc,