记录自己在学习c#遇到的知识点(容易忽略容易忘记得,或一些小技巧)
- using结构只是保证可以调用
cmd.Dispose()
方法 和connection.Dispose()
方法.而且不需要再包裹一层try{}catch{}
- get 传参后台可以设置参数类型,
[FromUri] Entity param
,
public HttpResponseMessage reportsExcel(HttpRequestMessage request,[FromUri] ExportParam param){
}
//其中ExportParam 类
public class ExportParam : ReportSearchParam
{
public string title { get; set; }
public string companyName { get; set; }
public DateTime date { get; set; }
public string[] tableTitles { get; set; }
}
此时,参数可以传递数组,但是数组的在url上的写法应是{{server}}Export/reportsExcel?companyId=1&startDate=2018-1-1&endDate=2018-2-1&title=测试&companyName=公司&date=2017-1-18&tableTitles=1111&tableTitles=aaa
,即,将数组参数重复写
- CallerMemberName,CallerFilePath,CallerLineNumber
/// <summary>
/// Writes an error level logging message.
/// </summary>
/// <param name="message">The message to be written.</param>
public void WriteError(object message,
[CallerMemberName] string memberName = "",//调用函数名称
[CallerFilePath] string sourceFilePath = "",//调用文件
[CallerLineNumber] int sourceLineNumber = 0 //调用行号)
{
_log4Net.ErrorFormat("文件:{0} 行号:{1} 方法名:{2},消息:{3}", sourceFilePath, sourceLineNumber, memberName, message);
}
- SortedDictionary
对一个Dictionary<TKey, TValue>进行键排序可以直接用SortedDictionary
SortedDictionary<TKey, TValue> 泛型类是检索运算复杂度为 O(log n) 的二叉搜索树。 就这一点而言,它与 SortedList<TKey, TValue> 泛型类相似。 这两个类具有相似的对象模型,并且都具有 O(log n) 的检索运算复杂度。
这两个类的区别在于内存的使用以及插入和移除元素的速度:
SortedList<TKey, TValue> 使用的内存比 SortedDictionary<TKey, TValue> 少,SortedDictionary<TKey, TValue> 可对未排序的数据执行更快的插入和移除操作:
它的时间复杂度为 O(log n),而 SortedList<TKey,TValue> 为 O(n),如果使用排序数据一次性填充,SortedList<TKey,TValue>比 SortedDictionary<TKey, TValue> 快。
每个键/值对都可以作为KeyValuePair<TKey, TValue> 结构进行检索,或作为DictionaryEntry通过非泛型IDictionary接口进行检索。只要键用作 SortedDictionary<TKey, TValue> 中的键,它们就必须是不可变的。
SortedDictionary<TKey, TValue> 中的每个键必须是唯一的。 键不能为 null,但是如果值类型 TValue 为引用类型,该值则可以为空。
SortedDictionary<TKey, TValue> 需要比较器实现来执行键比较。 可以使用一个接受 comparer 参数的构造函数来指定 IComparer<T> 泛型接口的实现;
如果不指定实现,则使用默认的泛型比较器 Comparer<T>.Default。
如果类型 TKey 实现 System.IComparable<T> 泛型接口,则默认比较器使用该实现。
对一个Dictionary<TKey, TValue>进行值排序可以用LINQ:
Dictionary<string, string> MyDictionary = new Dictionary<string, string>();
MyDictionary = (from entry in MyDictionary
orderby entry.Value ascending select entry).ToDictionary(pair => pair.Key, pair => pair.Value);
- 获取随机数
/// <summary>
/// 获取随机数
/// </summary>
/// <returns></returns>
private static string GetRandom()
{
Random rd = new Random(DateTime.Now.Millisecond);
int i= rd.Next(0,int.MaxValue);
return i.ToString();
}
- 获取时间戳
/// <summary>
/// 获取时间戳
/// </summary>
/// <returns></returns>
private static string GetTimeStamp()
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalMilliseconds).ToString();
}
网友评论