Extension interface patterns

后端 未结 11 2012
失恋的感觉
失恋的感觉 2020-12-14 16:56

The new extensions in .Net 3.5 allow functionality to be split out from interfaces.

For instance in .Net 2.0

public interface IHaveChildren {
    str         


        
11条回答
  •  独厮守ぢ
    2020-12-14 17:10

    I see separating the domain/model and UI/view functionality using extension methods as a good thing, especially since they can reside in separate namespaces.

    For example:

    namespace Model
    {
        class Person
        {
            public string Title { get; set; }
            public string FirstName { get; set; }
            public string Surname { get; set; }
        }
    }
    
    namespace View
    {
        static class PersonExtensions
        {
            public static string FullName(this Model.Person p)
            {
                return p.Title + " " + p.FirstName + " " + p.Surname;
            }
    
            public static string FormalName(this Model.Person p)
            {
                return p.Title + " " + p.FirstName[0] + ". " + p.Surname;
            }
        }
    }
    

    This way extension methods can be used similarly to XAML data templates. You can't access private/protected members of the class but it allows the data abstraction to be maintained without excessive code duplication throughout the application.

提交回复
热议问题