Public classUser {//Use the default parameters, generally do not need to do various static overloads for polymorphism PublicUser (stringName ="Anonym",stringType ="User") { This. UserName = name; This. usertype = type; } PublicUserName {PrivateSet Get } Publicusertype {PrivateSet Get }}user User =NewUser ();//without any parameter instantiationConsole.WriteLine (user. UserName);//Output anonymConsole.WriteLine (user. usertype);//Output userthe//dynamic keyword can bypass strong type checking for static languagesdynamic d = user; Console.WriteLine (D.username); //Output anonym Console.WriteLine (D.usertype); //output user //ExpandoObject is a special object that contains members that can be dynamically added or removed at run timeDynamic EO =NewSystem.Dynamic.ExpandoObject (); Eo. Description ="This was a dynamic property"; Console.WriteLine (EO. Description);//Output This was a dynamic property//Inherit DynamicObject class, override Tryinvokemember virtual method Public classAnimal:dynamicobject {//Try to execute the member, return true successfully, and output the returned value after execution from the second parameter Public Override BOOLTryinvokemember (Invokememberbinder Binder,Object[] args, out ObjectResult) {BOOLSuccess =Base. Tryinvokemember (binder, args, outresult);The //base class tries to execute the method, returns False, indicates that the method does not exist, out null value//if (! Success) result = NULL;//If return false throws an exceptionreturn true; } }//Derived dynamic class Public classDuck:animal { Public stringQuack () {return "quack!!"; } }//Derived dynamic class Public classHuman:animal { Public stringTalk () {return "talk!!"; } }//Invoke dynamic method Public Static stringDoquack (Dynamic animal) {stringresult = animal. Quack ();returnResult??"Null";//(result = = null)? "Human": result;}var Duck =NewDuck (); var human =NewHuman (); Console.WriteLine (Doquack (Duck));//Output QuackConsole.WriteLine (Doquack (Human));//Output Null, human class does not contain quack method, execution failed
C # 4 Dynamic dynamic Object type conversions