c# - 将参数传递给 C# 中的工厂模式体系结构

标签 c# asp.net

我想实现工厂模式架构。我创建了带有参数化函数的接口(interface)。

1) 第 1 步:

public  interface IDatabase
    {
        bool Create(string userId,string password,string host,string dbName);
        bool Delete(string userId, string password, string host, string dbName);
    }

第 2 步:

这个接口(interface)在下面的类中实现:-

public class IntialDBSetup : IDatabase
    {    
        public bool Create(string userId, string password, string host, string dbName)
        {
            SqlConnection con = new SqlConnection("Data Source=" + host + ";uid=" + userId + ";pwd=" + password + "");
            try
            {    
                string strCreatecmd = "create database " + dbName + "";
                SqlCommand cmd = new SqlCommand(strCreatecmd, con);
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();

                var file = new System.IO.FileInfo(System.Web.HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["ScriptLocation"]));
                string strscript = file.OpenText().ReadToEnd();
                string strupdatescript = strscript.Replace("[OWpress]", dbName);
                var server = new Microsoft.SqlServer.Management.Smo.Server(new Microsoft.SqlServer.Management.Common.ServerConnection(con));
                server.ConnectionContext.ExecuteNonQuery(strupdatescript);
                con.Close();
                return true;    
            }
            catch (Exception ex)
            {
                return false;    
            }               
        }    
        public bool Delete(string userId, string password, string host, string dbName)
        {
            throw new NotImplementedException();
        }
    }

第 3 步:

创建工厂类

public class DBFactory
{
   public static IDatabase DbSetup(string DbType, string userId, string password, string host, string dbName)
   {
       try
       {
           if (DbType == DBTypeEnum.IntialDB.ToString())
           {               
               return new IntialDBSetup();
           }             
       }
       catch (Exception ex)
       {
           throw new ArgumentException("DB Type Does not exist in our Record");             
       }
       return null;           
   }
}

这里我想传递一些参数给我的类,我能得到这个吗?

最佳答案

为您的类添加一个构造函数。

如果 DBFactoryIntialDBSetup 在同一个程序集中,那么该构造函数可以标记为 internal(防止程序集外部的代码直接创建实例) .

如果工厂方法是 IntialDBSetupstatic 成员,那么构造函数可以是 private,即使在同一个程序集中也可以防止直接创建。

关于c# - 将参数传递给 C# 中的工厂模式体系结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30459585/

相关文章:

c# - TcpClient 抛出 SocketException

c# - 检查数字是否为素数的更快方法?

c# - 使用 TCP 绑定(bind)将非托管 C++ 连接到 WCF

asp.net - 为什么需要 Server.HtmlEncode?

c# - javascript根据另一个下拉列表自动选择下拉列表

c# - 使用按键触发 Blazor 中的按钮时未设置对象引用

c# - 用C#绘制带有圆角,边框和渐变的图像

c# - 在一种方法中构造多个查询的最佳方法 c# asp.net

asp.net - 注销时删除 cookie

c# - 无法加载文件或程序集 'WebGrease' 它的依赖项之一。找到的程序集的 list 定义与程序集引用不匹配