简体   繁体   English

创建通用方法

[英]Creating Generic methods

I am here wanted to implement some methods that coverts a list of interface references to their respective class type and then return the list is unique in some sense. 我在这里想要实现一些方法,这些方法隐蔽了对各自类类型的接口引用的列表,然后在某种意义上返回唯一的列表。

Here is the 这里是

    public bool IsFilesHavingUniqueID(List<IFile> files)
    {
        List<File> _files = files.ConvertAll(x => (File)x).ToList();
        return _files.Distinct().ToList().Count == _files.Count; 
    }

    public bool IsTablesHavingUniqueID(List<ITable> tables)
    {
        List<Table> _tables = tables.ConvertAll(x => (Table)x).ToList();
        return _tables.Distinct().ToList().Count == tables.Count;
    }

Calling of these methods 调用这些方法

    public bool ValidateDIPObject(DIP dip)
    {
        // Validating Tabels
        IsFilesHavingUniqueID(dip.Files);

        // Validating Files
        IsTablesHavingUniqueID(dip.Tables);

        // ... continues 
    }

Is there any method I can write this code in a generic way. 有什么我可以通用的方式编写此代码的方法。 I have to write a bunch of methods with the same pattern so I think generic code will be the best option. 我必须用相同的模式编写一堆方法,因此我认为通用代码将是最佳选择。

Please help 请帮忙

You could do this: 您可以这样做:

public bool IsUnique<IView,T>(List<IView> ls) where T : class
{
    return ls.Cast<T>().Distinct().Count()==ls.Count();
}

You can simply specify type and interface as generic parameters: 您可以简单地将类型和接口指定为通用参数:

public bool IsTablesHavingUniqueID<TInterface, T>(List<TInterface> tables)
       where T:TInterface
{
    List<T> _tables = tables.ConvertAll(x => (T)x).ToList();
    return _tables.Distinct().ToList().Count == tables.Count;
}

This code assumes class correctly implements IEquatable<T> , GetHashCode and 此代码假定类正确实现了IEquatable<T>GetHashCode
Equals , if not - use other overrides of Distinct that take comparers. 如果不Equals ,则Equals -使用其他采用比较器的Distinct替代。

Note that code looks like partially incorrect implementation of OfType and possibly code can be re-written as: 请注意,代码看起来像OfType的部分错误实现,并且可能的代码可以重写为:

    tables.OfType<File>().Distinct().Count() == tables.Count();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM