首页 > 解决方案 > 将对象添加到列表的工厂方法

问题描述

我想寻求帮助,我需要用 Project 和 Employee 类的对象填写项目、员工表。我将非常感谢您的帮助。

class Menu
{
    public void menu()
    {
        List<Project> projects = new List<Project>();
        List<Employee> employees = new List<Employee>();
       // Manipulate selection of a menu item
        switch (menu)
        {
            case 1:
                CreateFunc(new EmployeeType());
                break;
            case 2:
                CreateFunc(new ProjectType());
                break;
        }
    }
    static void CreateFunc(CreateType create)
    {
        create.NewObject();
    }
}
abstract class CreateType
{
    public abstract ICreate Add();

    public void NewObject()
    {
        var createtype = Add();
        createtype.Adding();
    }
}

class ProjectType : CreateType
{
    public override ICreate Add()
    {
        return new Project();
    }
}

class EmployeeType : CreateType
{
    public override ICreate Add()
    {
        return new Employee();
    }
}

Interface 和 Project & Employee 类

标签: c#.net

解决方案


您的问题似乎有点不清楚,但是看着我的水晶球,您似乎需要方法Activator.CreateInstance

https://docs.microsoft.com/en-us/dotnet/api/system.activator.createinstance?view=netframework-4.8

静态类型创建

public class StaticFactory
{
  public static T StaticInstance<T>() where T : class, new()
  {
    var entityType = typeof(T);
    return (T) Activator.CreateInstance(entityType);
  }
}

用法

var model1 = StaticFactory.StaticInstance<Boss>();
var model2 = StaticFactory.StaticInstance<Boss>();
var models = new List<dynamic> { model1, model2 };

动态类型创建

public class DynamicFactory
{
  public static dynamic DynamicInstance(Type someType)
  {
    return Activator.CreateInstance(someType);
  }
}

用法

var model1 = DynamicFactory.DynamicInstance(typeof(Boss));
var model2 = DynamicFactory.DynamicInstance(someEmployeeVariable.GetType());
var models = new List<dynamic> { model1, model2 };

界面创建

public interface SomeInterface
{
  void DoWork();
}

public enum EnumType 
{
  Boss, 
  Employee
}

public class InterfaceFactory
{
  public static SomeInterface InterfaceInstance(EnumType enumType)
  {
    switch (enumType) 
    {
      case SomeType.Boss: return new Boss();
      case SomeType.Employee: return new Employee();
    }

    return null;
  }
}

用法

var model1 = InterfaceFactory.InterfaceInstance(EnumType.Boss);
var model2 = InterfaceFactory.InterfaceInstance(EnumType.Boss);
var models = new List<SomeInterface> { model1, model2 };

您还可以从父类型中提取基础类型,例如 int inList<int>

List<int> myList = ...
Type myListElementType = myList.GetType().GetGenericArguments().Distinct(); // all types in the list, in this case int

推荐阅读