首页 文章

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

提问于
浏览
2

我经常需要通过将实现委托给我的类的成员来实现接口 . 此任务非常繁琐,因为即使Visual Studio为接口方法生成存根,我仍然必须编写代码来委派实现 . 它不需要太多思考,因此它可能通过代码生成工具自动化......

我可能不是第一个想到这个的人,所以必须有这样的工具,但我在Google上找不到任何东西......任何想法?


编辑:它似乎ReSharper can do it,但它相当昂贵......是否有一个具有相同功能的免费替代品?

3 回答

  • 0

    我已经使用Resharper几个月了,它有一个很棒的功能来做到这一点 .

    例如,编写以下代码:

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

    将插入符号放在 _list 上,按Alt Ins(生成代码的快捷键),然后选择"Delegating members" . 选择您需要的成员,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; }
        }
    
  • 2

    ...看动态代理......

    然而...

    将接口实现委托给实例变量或类型[如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”之类的等价物)将使用名称和签名接口的正常名称和签名映射语义来标识“辅助”实现一个或多个接口的类字段值的有序列表 . 对应 . 任何本地实现都具有优先权,并且单个接口也可以由多个字段值实现 .

相关问题