如何动态实例化对象?

编程入门 行业动态 更新时间:2024-10-23 16:19:49
本文介绍了如何动态实例化对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试构建一个工厂类,该工厂类将为我提供不同DbContext的单例化实例。

I am trying to build a factory class that will feed me singleton-ized instances of different DbContexts.

主要思想是使 Dictionary< Type,DbContext> 将容纳我需要的所有实例,以及 GetDbContext(Type type)方法,该方法在字典并返回(如果已存在)。如果没有,则应该创建一个新的Type()并将其添加到相应的字典中。

The main idea is to have a Dictionary<Type,DbContext>that will hold all the instances I need , and a GetDbContext(Type type) method that looks up type in the dictionary and returns it if it already exists. If it doesn't it should create a new Type(), and add it to the corresponding dictionary.

我不知道该怎么做 contexts.Add(type,new type());

public class DbContextFactory { private readonly Dictionary<Type, DbContext> _contexts; private static DbContextFactory _instance; private DbContextFactory() { _contexts= new Dictionary<Type, DbContext>(); } public static DbContextFactory GetFactory() { return _instance ?? (_instance = new DbContextFactory()); } public DbContext GetDbContext(Type type) { if (type.BaseType != typeof(DbContext)) throw new ArgumentException("Type is not a DbContext type"); if (!_contexts.ContainsKey(type)) _contexts.Add(type, new type()); //<--THIS is what I have now Idea how to do return _contexts[type]; } }

推荐答案

制作它是一种通用方法:

Make it a generic method:

public DbContext GetDbContext<T>() where T : new() { if (typeof(T).BaseType != typeof(DbContext)) throw new ArgumentException("Type is not a DbContext type"); if (!_contexts.ContainsKey(type)) _contexts.Add(typeof(T), new T()); return _contexts[type]; }

更多推荐

如何动态实例化对象?

本文发布于:2023-08-04 17:37:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1298283.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:实例   对象   动态

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!