c#.NET动态对象名称

jw0*_*0rd 0 .net c# class dynamic

自上次我接触Java以来​​,我没有使用过Reflection,而且我有点生疏了.我创建了一个使用计时器的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;
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 6

没有"类实例名称"这样的东西.对象没有名称 - 变量没有名称.

现在也许你想要创建一个Dictionary<string, TestA>从"名称"到对象的地图......我不确定.您以后想如何使用这些名称?

Activator.CreateInstance如果你在执行时间之前不知道类型,通常是合适的.那是不是真的如此?在编译时你有什么信息,你只在执行时有什么信息?

当你说你想"将一些参数传递给默认构造函数"时 - 你到底是什么意思?通常,术语"默认构造函数"用于指代无参数构造函数1.您打算如何将参数传递给无参数构造函数?


1当你没有指定任何构造函数时,我更喜欢为编译器创建的无参数构造函数保留它,但是我们去了.