public static PennyFarthing CreateWithGears(int gears) { var penny = new PennyFarthing(1, 1); penny.Gear = gears; // Oops, can't do this! return(penny); }
public static void Classes() { // 使用new初始化对象 Bicycle trek = new Bicycle(); // 调用对象的方法 trek.SpeedUp(3); // 你应该一直使用setter和getter方法 trek.Cadence = 100; // 查看对象的信息. Console.WriteLine("trek info: " + trek.Info()); // 实例化一个新的Penny Farthing PennyFarthing funbike = new PennyFarthing(1, 10); Console.WriteLine("funbike info: " + funbike.Info()); Console.Read(); }
/////////////////////////////////////// // CLASSES - see definitions at end of file /////////////////////////////////////// public static void Classes() { // See Declaration of objects at end of file // Use new to instantiate a class Bicycle trek = new Bicycle(); // Call object methods trek.SpeedUp(3); // You should always use setter and getter methods trek.Cadence = 100; // ToString is a convention to display the value of this Object. Console.WriteLine("trek info: " + trek.Info()); // Instantiate a new Penny Farthing PennyFarthing funbike = new PennyFarthing(1, 10); Console.WriteLine("funbike info: " + funbike.Info()); Console.Read(); } // End main method
public static void OtherInterestingFeatures() { // OPTIONAL PARAMETERS MethodSignatures(3, 1, 3, "Some", "Extra", "Strings"); MethodSignatures(3, another: 3); // explicitly set a parameter, skipping optional ones // BY REF AND OUT PARAMETERS int maxCount = 0, count; // ref params must have value MethodSignatures(ref maxCount, out count); // EXTENSION METHODS int i = 3; i.Print(); // Defined below // NULLABLE TYPES - great for database interaction / return values // any value type (i.e. not a class) can be made nullable by suffixing a ? // <type>? <var name> = <value> int?nullable = null; // short hand for Nullable<int> Console.WriteLine("Nullable variable: " + nullable); bool hasValue = nullable.HasValue; // true if not null // ?? is syntactic sugar for specifying default value (coalesce) // in case variable is null int notNullable = nullable ?? 0; // 0 // ?. is an operator for null-propagation - a shorthand way of checking for null nullable?.Print(); // Use the Print() extension method if nullable isn't null // IMPLICITLY TYPED VARIABLES - you can let the compiler work out what the type is: var magic = "magic is a string, at compile time, so you still get type safety"; Console.WriteLine(magic); // magic = 9; will not work as magic is a string, not an int // GENERICS // var phonebook = new Dictionary <string, string>() { { "Sarah", "212 555 5555" } // Add some entries to the phone book }; // Calling SETDEFAULT defined as a generic above Console.WriteLine(SetDefault <string, string>(phonebook, "Shaun", "No Phone")); // No Phone // nb, you don't need to specify the TKey and TValue since they can be // derived implicitly Console.WriteLine(SetDefault(phonebook, "Sarah", "No Phone")); // 212 555 5555 // LAMBDA EXPRESSIONS - allow you to write code in line Func <int, int> square = (x) => x * x; // Last T item is the return value Console.WriteLine(square(3)); // 9 // ERROR HANDLING - coping with an uncertain world try { var funBike = PennyFarthing.CreateWithGears(6); // will no longer execute because CreateWithGears throws an exception string some = ""; if (true) { some = null; } some.ToLower(); // throws a NullReferenceException } catch (NotSupportedException) { Console.WriteLine("Not so much fun now!"); } catch (Exception ex) // catch all other exceptions { throw new ApplicationException("It hit the fan", ex); // throw; // A rethrow that preserves the callstack } // catch { } // catch-all without capturing the Exception finally { // executes after try or catch } // DISPOSABLE RESOURCES MANAGEMENT - let you handle unmanaged resources easily. // Most of objects that access unmanaged resources (file handle, device contexts, etc.) // implement the IDisposable interface. The using statement takes care of // cleaning those IDisposable objects for you. using (StreamWriter writer = new StreamWriter("log.txt")) { writer.WriteLine("Nothing suspicious here"); // At the end of scope, resources will be released. // Even if an exception is thrown. } // PARALLEL FRAMEWORK // https://devblogs.microsoft.com/csharpfaq/parallel-programming-in-net-framework-4-getting-started/ var words = new List <string> { "dog", "cat", "horse", "pony" }; Parallel.ForEach(words, new ParallelOptions() { MaxDegreeOfParallelism = 4 }, word => { Console.WriteLine(word); } ); // Running this will produce different outputs // since each thread finishes at different times. // Some example outputs are: // cat dog horse pony // dog horse pony cat // DYNAMIC OBJECTS (great for working with other languages) dynamic student = new ExpandoObject(); student.FirstName = "First Name"; // No need to define class first! // You can even add methods (returns a string, and takes in a string) student.Introduce = new Func <string, string>( (introduceTo) => string.Format("Hey {0}, this is {1}", student.FirstName, introduceTo)); Console.WriteLine(student.Introduce("Beth")); // IQUERYABLE<T> - almost all collections implement this, which gives you a lot of // very useful Map / Filter / Reduce style methods var bikes = new List <Bicycle>(); bikes.Sort(); // Sorts the array bikes.Sort((b1, b2) => b1.Wheels.CompareTo(b2.Wheels)); // Sorts based on wheels var result = bikes .Where(b => b.Wheels > 3) // Filters - chainable (returns IQueryable of previous type) .Where(b => b.IsBroken && b.HasTassles) .Select(b => b.ToString()); // Map - we only this selects, so result is a IQueryable<string> var sum = bikes.Sum(b => b.Wheels); // Reduce - sums all the wheels in the collection // Create a list of IMPLICIT objects based on some parameters of the bike var bikeSummaries = bikes.Select(b => new { Name = b.Name, IsAwesome = !b.IsBroken && b.HasTassles }); // Hard to show here, but you get type ahead completion since the compiler can implicitly work // out the types above! foreach (var bikeSummary in bikeSummaries.Where(b => b.IsAwesome)) { Console.WriteLine(bikeSummary.Name); } // ASPARALLEL // And this is where things get wicked - combine linq and parallel operations var threeWheelers = bikes.AsParallel().Where(b => b.Wheels == 3).Select(b => b.Name); // this will happen in parallel! Threads will automagically be spun up and the // results divvied amongst them! Amazing for large datasets when you have lots of // cores // LINQ - maps a store to IQueryable<T> objects, with delayed execution // e.g. LinqToSql - maps to a database, LinqToXml maps to an xml document var db = new BikeRepository(); // execution is delayed, which is great when querying a database var filter = db.Bikes.Where(b => b.HasTassles); // no query run if (42 > 6) // You can keep adding filters, even conditionally - great for "advanced search" functionality { filter = filter.Where(b => b.IsBroken); // no query run } var query = filter .OrderBy(b => b.Wheels) .ThenBy(b => b.Name) .Select(b => b.Name); // still no query run // Now the query runs, but opens a reader, so only populates as you iterate through foreach (string bike in query) { Console.WriteLine(result); } }