代码之家  ›  专栏  ›  技术社区  ›  Will Marcouiller

通用接口与通用方法?

  •  0
  • Will Marcouiller  · 技术社区  · 14 年前

    我正在编写一个通用类型来处理底层的Active Directory对象,如组、组织单位和用户。

    我还在通用接口中使用“手动”依赖项注入。我想知道,在我的情况下,哪一个更合适:通用接口还是通用方法?

    下面是一个简化的代码示例:

    public interface IDirectorySource<T> where T : IDirectoryEntry {
        IDirectorySearcher<T> Searcher { get; }
    
        CustomSet<T> ToList(); // Related to my question, as I will here only return Searcher.ToList();
    }
    
    public interface IDirectorySearcher<T> where T : IDirectoryEntry {
        DirectorySearcher NativeSearcher { get; }
    
        CustomSet<T> ToList(); // Related to my question...
    }
    
    public sealed class GroupSearcher : IDirectorySearcher<Group> {
        public GroupSearcher(DirectoryEntry root, SearchScope scope) {
            // Instantiating...
        }
    
        public DirectorySearcher NativeSearcher { get; private set; }
    
        public CustomSet<T> ToList() { // That is the point of my question.
            // Listing all T objects found in AD...
        }
    }
    
    public sealed class DirectorySource<T> : IDirectorySource<T> where T : IDirectoryEntry {
    
        public DirectorySource(IDirectorySearcher<T> searcher) {
            Searcher = searcher;
        }
    
        public IDirectorySearcher<T> Searcher { get; private set; }
    
        public CustomSet<T> ToList() { // Here's the point to my question.
            return Searcher.ToList();
        }
    }
    

    所以,这就是我的观点。我想做我的 IDirectorySource 非通用接口,因为我将提升 DirectorySource<T> 类到 公众的 . 所以我只需要声明这样一个来源:

    GroupSearcher groupSearcher = new GroupSearcher(root, scope);
    IDirectorySource groups = new DirectorySource<Group>(groupSearcher);
    

    因此,我可以检索以下组的列表:

    groups.ToList(); // Getting all the existing groups in AD here...
    

    但我想知道我是否应该 IDirectorySource<T> 接口通用,或使其非通用,并使我的 IDirectorySource.ToList() 方法是泛型的,因此我不需要键入接口,只需要为我提供接口实例的类。

    最好这样写我的界面:

    public interface IDirectorySource {
        CustomSet<T> ToList<T>();
    } // With all the appropriate changes, indeed.
    

    我知道这可能还不够清楚。你可以问我你的问题,这样我可以帮助你帮助我。

    事先谢谢!=)

    1 回复  |  直到 14 年前
        1
  •  1
  •   Ed Noepel    14 年前

    对于 同一实例 属于 I直接来源 ,是否需要调用方法(例如 托利斯特 )使用不同类型?

    如果没有,那么离开 I直接来源 通用和方法( 托利斯特 )非能量的将使代码更清晰,允许对象从 I直接来源 实现自己的类型感知逻辑。