代码改变世界

.NET 4.0 里的默认参数原来是编译器搞的鬼啊

2011-07-07 21:39  音乐让我说  阅读(301)  评论(1编辑  收藏  举报

一个简单的例子来演示:

    public static class StringExtender
    {
        /// <summary>
        /// 字符串拼接
        /// </summary>
        /// <param name="item">原字符串</param>
        /// <param name="result">需要拼接的字符串</param>
        /// <param name="word">连接字符或字符串</param>
        /// <returns>结果</returns>
        public static string AppendWord(this string item, string result, string word = "_")
        {
            return item + word + result;
        }
    }

Program.cs

    class Program
    {
        static void Main(string[] args)
        {
            string word = "Hello";

            Console.WriteLine("默认参数:" + word.AppendWord("World"));
            Console.WriteLine("指定参数:" + word.AppendWord("World", "$"));
            Console.ReadKey();
        }
    }

编译后,我们Reflector一下。

Reflector后,我们的StringExtender:

Reflector后,我们的Main函数:

亲,最后要注意哦,由于默认参数是编译器搞的鬼,编译时帮你插入参数的,所以最好保证编译版本一致,即要同时更新引用的 DLL,并且重新编译目标项目。

谢谢浏览!