Extension interface patterns

后端 未结 11 2011
失恋的感觉
失恋的感觉 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:09

    I needed to solve something similar: I wanted to have a List passed to the extensions function where IIDable is an interface that has a long getId() function. I tried using GetIds(this List bla) but the compiler didn't allow me to do so. I used templates instead and then type casted inside the function to the interface type. I needed this function for some linq to sql generated classes.

    I hope this helps :)

        public static List GetIds(this List original){
            List ret = new List();
            if (original == null)
                return ret;
    
            try
            {
                foreach (T t in original)
                {
                    IIDable idable = (IIDable)t;
                    ret.Add(idable.getId());
                }
                return ret;
            }
            catch (Exception)
            {
                throw new Exception("Class calling this extension must implement IIDable interface");
            }
    

提交回复
热议问题