C#基础语法实例荟萃

匿名类

action = new UploadHandler(context, new UploadConfig()
{
     AllowExtensions = Config.GetStringList("imageAllowFiles"),
     PathFormat = Config.GetString("imagePathFormat"), //设置上传图片的保存路径及文件名模板
     SizeLimit = Config.GetInt("imageMaxSize"),
     UploadFieldName = Config.GetString("imageFieldName")
});

delegate 传递匿名方法

所谓的delegate 传递匿名方法

//使用ThreadPool开启线程
//无参数传递
private void DoWork() {
    ThreadPool.QueueUserWorkItem(new WaitCallback(this.DoSomething));
}
private void DoSomething(object o) {
    MessageBox.Show("thread start");
}
//有参数传递
private void DoWork() {
    ThreadPool.QueueUserWorkItem(new WaitCallback(this.DoSomething), "guozhijian");
}
private void DoSomething(object o) {
    MessageBox.Show(o.ToString());
}
//使用匿名方法更灵活,即使用delegate向WaitCallback出入匿名方法体 
//即delegate + 一个没有名称方法(参数列表+方法体)
private void DoWork() {
    string name = "guozhijian";
    ThreadPool.QueueUserWorkItem(new WaitCallback(delegate(object o){
        MessageBox.Show(name);
    }));
}

as和is 

as与is做差不多的事情,类型显式强制转换。
as操作符的工作方式与强制类型转换一样,只是它永远不会抛出一个异常——相反,如果对象不能转换,结果就是null。

Object obj=new Object(); 
ClassA a= obj  as ClassA;
if(a!=null)  //在if判断a是否为null, 因为如果obj不兼容类型ClassA,as将返回null赋值给a
{
...
}

?? 

??  判断不为null,然后执行

public PagedList(IEnumerable<T> allItems, int pageIndex, int pageSize)
{
     PageSize = pageSize;
     var items = allItems as IList<T> ?? allItems.ToList();
     TotalItemCount = items.Count();
     CurrentPageIndex = pageIndex;
     AddRange(items.Skip(StartItemIndex - 1).Take(pageSize));
}

 

string result = (Cache[cacheKey] ?? "N").ToString();

 匿名类和数组

new[] { "Xxx" }
Tag[] result = {
    new Tag {
        tagName = "Vue",
        total = 9
    },
    new Tag {
        tagName = "Vue",
        total = 9
    }
};
public class Tag
{
    public int total { get; set; }

    public string tagName { get; set; }
}
string[] staticFileList = {
                 "index.html",
                 "news_list_jt.html",
                 "news_list_gs.html",
                 "news_list_yw.html",
                 "news_list_jiaojuguoqi.html"
};
staticFileList = new string[] { };

 

posted @ 2016-01-15 14:27  轴轴  阅读(454)  评论(0编辑  收藏  举报