首页 > c# > C# 3.0 新特性之隐含类型局部变量

C# 3.0 新特性之隐含类型局部变量

C# 3.0 新特性隐含类型局部变量(Local Variable Type Inference)

一般情况下我们可以定义如下变量
    int i = 43;

    string s = "...This is only a test...";

    int[] numbers = new int[] { 4, 9, 16};

    SortedDictionary<string, List<DateTime>> complex =
        new SortedDictionary<string, List<DateTime>>();
==================================================================
var 可变变量的定义则如下定义:
            var i = 43;

            var s = "...This is only a test...";

            var numbers = new[] { 4, 9, 16 };

            var complex = new SortedDictionary<string, List<DateTime>>();
这些变量在调试的时候可以把鼠标放到var上,则var则显示定义的类型
==================================================================
var 隐含类型数组如何正确定义
错误的定义如下
var x;// 错误,因为这样不知道什么类型
    x = new int[] { 1, 2, 3 };

var x = {1, 2, 3}; // var数组这样的定义是不允许的

var x = new[] {1, 2, 3};//正确定义

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace NewLanguageFeatures
{
    public class Customer
    {
        public int CustomerId { get; private set; }

        public string Name { get; set; }
        public string City { get; set; }

        public Customer(int Id)
        {
            CustomerId = Id;
        }

        public override string ToString()
        {
            return Name + "\t" + City + "\t" + CustomerId;
        }
    }

    class Program
    {
        static void VarTest()
        {
            var x = new[] { 1, 2, 3 };//var数组的定义
        }

        static void Main(string[] args)
        {
            var customers = CreateCustomers();//var 方法定义

            Console.WriteLine("Customers:\n");
            foreach (var c in customers)//var 参数定义
                Console.WriteLine(c);
        }

        static List<Customer> CreateCustomers()
        {
            return new List<Customer>
                {
                    new Customer(1) { Name = "Alex Roland",             City = "Berlin"    },
                    new Customer(2) { Name = "Oliver Cox",              City = "Marseille" },
                    new Customer(3) { Name = "Maurice Taylor",          City = "London"    },
                    new Customer(4) { Name = "Phil Gibbins",            City = "London"    },
                    new Customer(5) { Name = "Tony Madigan",            City = "Torino"    },
                    new Customer(6) { Name = "Elizabeth A. Andersen",   City = "Portland"  },
                    new Customer(7) { Name = "Justin Thorp",            City = "London"    },
                    new Customer(8) { Name = "Bryn Paul Dunton",        City = "Portland"  }
                };
        }      
    }
}

原创文章转载请注明出处:云飞扬IT的blog

本文链接: http://www.ajaxcn.net/archives/178

分类: c# 标签: ,
一键分享到:新浪微博分享  分享到网易微博    转贴到开心网  推荐到豆瓣  分享到QQ空间    RSS订阅
  1. 本文目前尚无任何评论.
  1. 本文目前尚无任何 trackbacks 和 pingbacks.