【问题标题】:c# .NET dynamic object namec# .NET 动态对象名称
【发布时间】:2010-11-15 21:45:52
【问题描述】:

自从我上次接触 Java 以来,我就没有使用过反射,我有点生疏了。我创建了一个使用计时器的 Windows 服务,并且对于某些类,我需要动态的对象名称(从 sql 表中提取)。对象的创建范围在一个 while 循环内,我需要能够保存每个对象的属性。

编辑:

最后使用了字典,以便我以后可以检索每个对象的属性。

    private void GetActiveScans()
    {
        string sql = "SELECT * FROM scans WHERE enabled = 1";
        SqlConnection sqlconn = new SqlConnection(connectionString);
        sqlconn.Open();
        SqlCommand cmd = new SqlCommand(sql, sqlconn);
        SqlDataReader drActiveScans = cmd.ExecuteReader(CommandBehavior.CloseConnection);

        Dictionary<int, WindowsServiceAudit> WSA = new Dictionary<int, WindowsServiceAudit>();

        while (drActiveScans.Read())
        {
            string tmpscantype = drActiveScans["scantype"].ToString();

            switch (tmpscantype)
            {
                case "services":
                    int scanid = Convert.ToInt32(drActiveScans["scanid"]);
                    string scanname = drActiveScans["scanname"].ToString();
                    int serverclass = Convert.ToInt32(drActiveScans["serverclass"]);
                    int interval = Convert.ToInt32(drActiveScans["interval"]);

                    WindowsServiceAudit x = new WindowsServiceAudit(scanid, scanname, serverclass, interval);
                    WSA.Add(scanid, x);                
                    break;
            }
        }
    }

【问题讨论】:

  • 哇,这是迄今为止我见过的最疯狂的问题!

标签: c# .net class dynamic


【解决方案1】:

没有“类实例名称”之类的东西。对象没有名称 - 变量有。

现在也许您想创建一个Dictionary&lt;string, TestA&gt; 来创建从“名称”到对象的映射...我不确定。您想以后如何使用这些名称?

Activator.CreateInstance 通常是合适的,如果你不知道 type 直到执行时间。事实是这样,还是不是?您在编译时拥有哪些信息,而您仅在执行时拥有哪些信息?

当您说您想“将多个参数传递给默认构造函数”时,您究竟是什么意思?通常术语“默认构造函数”用于指代无参数构造函数1。您打算如何将参数传递给无参数构造函数?


1 当你根本没有指定任何构造函数时,我更喜欢将它保留给编译器创建的无参数构造函数,但是我们开始了。

【讨论】:

  • 是的!使用字典。不是反思。 +1
  • 是的,我认为字典是他能够使用字符串名称的唯一方法。我怀疑他在问如何实施他已经决定的解决方案。
  • 1) 对不起,不是默认构造函数,只是一个构造函数。 2) 是的,听起来像字典一样。
猜你喜欢
  • 2023-03-27
  • 2021-03-13
  • 2015-12-12
  • 2010-12-20
  • 2013-09-27
  • 1970-01-01
  • 1970-01-01
  • 2011-02-20
  • 2012-11-11
相关资源
最近更新 更多