简体   繁体   English

C#以单一方法将通用接口派生的对象添加到集合中

[英]C# Add Objects Derived Of A Common Interface to a Collection in a Single Method

I have two types of objects, sharing a common interface. 我有两种类型的对象,共享一个公共接口。 I need to create these objects from data stored in two different tables in a database and formatted into two separate .NET DataTables. 我需要根据存储在数据库中两个不同表中的数据创建这些对象,并将其格式化为两个单独的.NET DataTable。

These objects are fundamentally the same, with some distinct properties for each. 这些对象基本上是相同的,每个对象都有一些不同的属性。

 public interface IRecord
{
     int Record_ID { get; set; }
     //Other Properties
}

Class TypeA: IRecord
Class TypeB: IRecord

DataTable TypeARecords
DataTable TypeBRecords

The Problem 问题

I need these objects in a single collection of type IRecord, which is of class scope. 我需要在类范围为IRecord的单个集合中使用这些对象。

I currently have two methods that handle the creation of each type of object and add it to the collection. 我目前有两种方法可以处理每种类型的对象的创建并将其添加到集合中。 These methods are identical with the exception of the objects being worked with. 除了使用的对象外,这些方法相同。 I would like to combine these into a single method that accomplishes the following: 我想将它们组合成一个实现以下目标的方法

  1. Determine what type of object should be created. 确定应创建哪种类型的对象。
  2. Determine if that object already exists in the collection using the type of the object and the 'RECORD_ID' 使用对象的类型和“ RECORD_ID”确定该对象在集合中是否已存在
  3. Add the objects to a single collection of type IRecord 将对象添加到IRecord类型的单个集合中

Here is an example of the method that acts on objects of TypeA 这是作用于TypeA对象的方法的示例

List<IRecord> records; //This may or may not have anything in it, initially.

private void CreateTypeAObjects()
{

     DataTable TypeARecords = GetDataMethod();


        foreach (DataRow row in TypeARecords.Rows)
        {
            int recordID = int.Parse(row["Record_ID"].ToString());


            if (records != null && records.Count > 0)
            {
                //If the record is of TypeA and doesn't have an existing object in the collection, create it.
                if ((!records.Where(t => t is TypeA).Any(s => s.Record_ID == recordID)))
                {
                    records.Add(new TypeA
                    {
                        Record_ID = int.Parse(row["Record_ID"].ToString()),
                        //Initialize other properties
                    });

                }
            }
            else
            {
           //If the list is not instantiated, create it now and add record.
                records = new List<IRecord>();
                records.Add(new TypeA
                {
                    Record_ID = int.Parse(row["Record_ID"].ToString()),
                    //Initialize Other Properties

                });
            }

        }
}

You could pass in the DataTable and the Type into the GetDataMethod() function. 您可以将DataTable和Type传入GetDataMethod()函数。

List<IRecord> records = new List<IRecord>();

private void CreateAllObjects(System.Type _type, DataTable table)
{

    foreach (DataRow row in table.Rows)
    {
        int recordID = int.Parse(row["Record_ID"].ToString());


        //If the record is of the passed in type and doesn't have an existing object in the collection, create it.
        if ((!records.Where(t => t is _type).Any(s => s.Record_ID == recordID)))
            {

                IRecord record = (IRecord)Activator.CreateInstance(_type);
                //initialize record
                records.Add(record);

            }  

    }
}

A DataTable is a DataTable and you can use the Activator to instantiate each type. DataTable是一个DataTable,您可以使用Activator实例化每种类型。

You call that function twice to get your data loaded. 您调用该函数两次以加载数据。 I took the liberty of simplifying your logic based on the assumption that I could initialize the records list when it is declared. 我自由地假设您可以在声明时初始化记录列表,从而简化了您的逻辑。

CreateAllObjects(TypeA, TypeARecords);
CreateAllObjects(TypeB, TypeBRecords);

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

相关问题 多个派生类的C#单类收集方法 - C# Single Generic Collection Method for Multiple Derived Classes 向从 C# 接口继承的类添加通用方法? - Add common method to classes inheriting from a C# Interface? C#::何时使用事件或从事件处理接口派生的对象集合? - C#:: When to use events or a collection of objects derived from an event handling Interface? C#:将基础 class 集合对象复制到派生的 class 对象中 - C#: copy base class collection objects into derived class objects 将派生类的方法重构为公共基类的方法? (C#) - Refactoring Derived Classes' Methods to Common Base Class' Method? (C#) C#-接口通用方法约束以匹配派生类型 - C# - Interface generic method constraint to match derived type 如何将派生的 object 添加到从同一接口继承但使用 generics 的对象集合中? - How do I add a derived object to a collection of objects which inherit from the same interface, but use generics? 具有派生接口的C#接口实现 - C# interface implementation with derived interface C# .NET 将 InterfaceImplementingClass 对象的集合传递给采用 Interface 对象集合的例程 - C# .NET passing a collection of InterfaceImplementingClass objects to a routine that takes a collection of Interface objects c#中是否有快捷方式可以在整个集合上调用接口方法? - Is there a shortcut in c# to invoke a interface method on an entire collection?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM