coding snippet
yield keyword
by calendarw on Oct.29, 2009, under coding snippet
近期因為睇 ASP.net MVC 既 example, 中途見到 yield keyword 既 usage, 感覺上幾好用, 以學多個 keyword 既原則黎講, 我當然會在 project 中試用, 當中既 validation 用法我覺得幾好.
public partial class Dinner {
public bool IsHostedBy(string userName) {
return HostedBy.Equals(userName, StringComparison.InvariantCultureIgnoreCase);
}
public bool IsValid {
get { return (GetRuleViolations().Count() == 0); }
}
public IEnumerable<RuleViolation> GetRuleViolations() {
if (String.IsNullOrEmpty(Title))
yield return new RuleViolation("Title is required", "Title");
if (String.IsNullOrEmpty(Description))
yield return new RuleViolation("Description is required", "Description");
if (String.IsNullOrEmpty(HostedBy))
yield return new RuleViolation("HostedBy is required", "HostedBy");
if (String.IsNullOrEmpty(Address))
yield return new RuleViolation("Address is required", "Address");
if (String.IsNullOrEmpty(Country))
yield return new RuleViolation("Country is required", "Address");
if (String.IsNullOrEmpty(ContactPhone))
yield return new RuleViolation("Phone# is required", "ContactPhone");
if (!PhoneValidator.IsValidNumber(ContactPhone, Country))
yield return new RuleViolation("Phone# does not match country", "ContactPhone");
yield break;
}
}
但當我想在 project 度用果時, 開始感覺到麻煩, 因為本身個 project 係要在 .net 2.0 既環境下運作, 而 IEnumerable
List.Sort – Lambda Expression Way
by calendarw on Aug.18, 2009, under coding snippet
呢期研究既 delegation, 其中一個例子係 Lambda 在 List
List<Person> persons = new List<Person>(); // sort by name persons.Sort((a,b) => a.Name.CompareTo(b.Name)); // sort by age persons.Sort((a,b) => a.Age.CompareTo(b.Age)); bool ascending = false; // descending by age persons.Sort((a,b) => a.Age.CompareTo(b.Age) * (ascending ? 1 : -1));
有了這樣既 syntax, 寫 sorting 易左同快捷左很多~~
C# as operator
by calendarw on Aug.04, 2009, under coding snippet
as operator 係用黎做 casting 的
static void Main()
{
double x = 1234.7;
int a;
// Cast double to int.
a = (int)x;
System.Console.WriteLine(a);
}
// Output: 1234
如果用 boxing 黎轉 type 既話, 錯 type 的話就會 throw InvalidCastException, 但如果用 as operator 就唔會 throw InvalidCastException, 而 value 就會係 null
public static void Main()
{
object time1 = DateTime.Now;
DateTime? t = time1 as DateTime?; // valid casting
int? wrongCast = time1 as int?; // wrongCast == null
}
C# ?? null coalescing operator
by calendarw on Jul.23, 2009, under coding snippet
null coalescing operator – ?? 係用黎決定參數是否 null 既算式, 自 C# 2.0 開始支援, 作為 null 既使用簡化.
// .net framework 1.1 既寫法
if (obj.Currency != null)
cbxCurrency.SelectedItem = obj.Currency;
else
cbxCurrency.SelectedItem = DefaultCurrency;
// .net framework 2.0 既寫法 cbxCurrency.SelectedItem = obj.Currency ?? DefaultCurrency;
長度上係短左, 識既人會易睇左. 另一方面, 通常既用法會同 Nullable 一齊用, 但自己平時無乜用開 Nullable, 所以對此無乜 comment (知道有呢樣野, 但唔知咩情況用先叫做適合, 所以都未用過.
// nullable int int? i = null; int result = i ?? 5; // Output: result == 5
Timer for Performance Testing
by calendarw on May.13, 2009, under coding snippet, testing
呢排重溫緊 Pragmatic Unit Testing in C# with Nunit, 開始試緊寫有關 Performance 既 Test Case, 書中有一段有關 Performance 既 Code:
[Test]
public void FilterRanges()
{
Timer timer = new Timer();
String naughty_url = "http://www.xxxxxxxxxxx.com";
// First, check a bad URL against a small list
URLFilter filter = new URLFilter(small_list);
timer.Start();
filter.Check(naughty_url);
timer.End();
Assert.IsTrue(timer.ElapsedTime < 1.0);
// Next, check a bad URL against a big list
filter = new URLFilter(big_list);
timer.Start();
filter.Check(naughty_url);
timer.End();
Assert.IsTrue(timer.ElapsedTime < 2.0);
// Finally, check a bad URL against a huge list
filter = new URLFilter(huge_list);
timer.Start();
filter.Check(naughty_url);
timer.End();
Assert.IsTrue(timer.ElapsedTime < 3.0);
}
段 code 係一個幾好既 example 去講點 Test Performance, 但當真係要試果陣, 就發現左樣野, 就係我搵唔到 Code 中既 Timer Class, 係我在 System 入面既幾個 namespace 中, 都搵唔到啱用既 Timer, 因為 System namespace 入面既 Timer 大部份都係用黎 Trigger Timeout Event, 而當中既 Stop method 都只係用黎停止 Event Trigger, 而沒有任何計時結果做到出黎, 所以經過一輪網上既搜尋之後, 得出以下 Timer, 主要目的係用黎計時, 仔細度高, 最啱用黎作 Performance Testing 之用!!~
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace TestUtil
{
public class HighResolutionTimer
{
private long frequency;
private long start;
private long stop;
public HighResolutionTimer()
{
QueryPerformanceFrequency(ref frequency);
}
public float ElapsedTime
{
get
{
float elapsed = (((float)(stop - start)) / ((float)frequency));
return elapsed;
}
}
public void Start()
{
QueryPerformanceCounter(ref start);
}
public void Stop()
{
QueryPerformanceCounter(ref stop);
}
[System.Runtime.InteropServices.DllImport("KERNEL32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
private static extern bool QueryPerformanceCounter([In, Out] ref long performanceCount);
[System.Runtime.InteropServices.DllImport("KERNEL32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
private static extern bool QueryPerformanceFrequency([In, Out] ref long frequency);
}
}
HighResolutionTimer 來源 : 在 C# 中實現高性能計時
