日期:2014-05-20 浏览次数:20819 次
dynamic dyn = 1; Console.WriteLine(dyn.GetType()); dyn = 1.234; Console.WriteLine(dyn.GetType()); dyn = "ojlovecd"; Console.WriteLine(dyn.GetType()); /* 输出: System.Int32 System.Double System.String */
object obj = 10; obj = obj + 10;
object obj = 10; obj = (int)obj + 10;
object obj = 10; obj = (string)obj + 10; /* Unhandled Exception: System.InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.String'. */
dynamic dyn = 10; dyn = dyn + 10; Console.WriteLine(dyn); dyn = 10.02; dyn = dyn + 10; Console.WriteLine(dyn); dyn = "ojlovecd"; dyn = dyn + 10; Console.WriteLine(dyn);
dynamic dyn = 10; dyn = dyn + DateTime.Now; Console.WriteLine(dyn); /* Unhandled Exception: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: Oper ator '+' cannot be applied to operands of type 'int' and 'System.DateTime' at CallSite.Target(Closure , CallSite , Object , DateTime ) at System.Dynamic.UpdateDelegates.UpdateAndExecute2[T0,T1,TRet](CallSite site , T0 arg0, T1 arg1) at ConsoleApplication3.Program.Main(String[] args) in D:\CSharpProj\ConsoleAp plication3\ConsoleApplication3\Program.cs:line 26 */
static void Main(string[] args) { TestMethod(); TestMethod(3); } static void TestMethod(int i = 10) { Console.WriteLine(i); }
static void Main(string[] args) { TestMethod("hello"); } static void TestMethod(int i = 10, string s = "ojlovecd") { Console.WriteLine("i:{0},s:{1}", i, s); }