代码之家  ›  专栏  ›  技术社区  ›  Thomas Levesque

通过委派生成接口实现的工具?

  •  2
  • Thomas Levesque  · 技术社区  · 17 年前

    我经常需要通过将实现委托给类的成员来实现接口。这个任务相当乏味,因为即使VisualStudio为接口方法生成存根,我仍然必须编写代码来委托实现。它不需要太多的思考,所以它可能会被一个代码生成工具自动化。。。

    我可能不是第一个想到这个的人,所以肯定已经有这样一个工具了,但是我在谷歌上找不到任何东西。。。有什么想法吗?


    编辑:看来 ReSharper can do it

    3 回复  |  直到 17 年前
        1
  •  2
  •   Thomas Levesque    15 年前

    例如,编写以下代码:

    class MyList<T> : IList<T>
    {
        private readonly IList<T> _list;
    }
    

    将插入符号放在 _list 按 中高音 + (生成代码的快捷方式),然后选择“委派成员”。选择您需要的成员,R#为他们生成委派成员:

        public void Add(T item)
        {
            _list.Add(item);
        }
    
        public void Clear()
        {
            _list.Clear();
        }
    
        public bool Contains(T item)
        {
            return _list.Contains(item);
        }
    
        public void CopyTo(T[] array, int arrayIndex)
        {
            _list.CopyTo(array, arrayIndex);
        }
    
        public bool Remove(T item)
        {
            return _list.Remove(item);
        }
    
        public int Count
        {
            get { return _list.Count; }
        }
    
        public bool IsReadOnly
        {
            get { return _list.IsReadOnly; }
        }
    
        public int IndexOf(T item)
        {
            return _list.IndexOf(item);
        }
    
        public void Insert(int index, T item)
        {
            _list.Insert(index, item);
        }
    
        public void RemoveAt(int index)
        {
            _list.RemoveAt(index);
        }
    
        public T this[int index]
        {
            get { return _list[index]; }
            set { _list[index] = value; }
        }
    
        3
  •  1
  •   George    16 年前

    ... 请参阅动态代理。。。

    然而。。。

    将接口实现委托给实例变量或类型[如typeof(type)]的能力是C#和VB.Net非常需要的语言特性。由于缺少多重继承以及密封和非虚拟方法和属性的流行,所需的松散代码数量令人望而生畏。

    我认为下面的语言增强会起作用。。。 //C#

    interface IY_1
    {
      int Y1;
      int Y2;
    }
    ...
    ..
    interface IY_n
    {
    ....
    ..
    }
    
    
    class Y : IY_1, IY_2, ....,IY_n
    {
      private readonly Oy_1 Oy_1 = new Oy_1() supports IY_1, IY_2,...etc;   // <<-----
      private readonly Oy_2 Oy_2 = new Oy_2() supports IY_3, IY_8,...etc;
      public int Y2 {...}
    }
    

    “supports”关键字(或“defaults”等等效项)将标识类字段值的有序列表,这些值使用名称和签名对应接口的正常名称和签名映射语义“帮助”实现一个或多个接口。任何本地实现都具有优先权,并且单个接口可以由多个字段值实现。