I'm CaLendarW Blog

yield keyword

by 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.Count 係未有支援, 而且無 extension methods 既支援, 所以要另外寫個 class 黎 handle 呢樣野都幾麻煩, 因此我都無乜 idea 在其他方面可以實際上使用得適當……

:

Leave a Reply

You must be logged in to post a comment.

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!