views:

679

answers:

1

I haven't worked with Reflection since the last time I touched Java and I'm a little rusty. I've created a Windows service that uses timers and for some of the classes I need the object name to be dynamic (pulled from a sql table). The scope of the objects' creation is within a while loop and I need to be able to save each object's properties.

EDIT:

Ended up using a dictionary so that I can retrieve each object's properties later.

    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;
            }
        }
    }
+6  A: 

There's no such thing as a "class instance name." An object doesn't have a name - a variable does.

Now maybe you want to create a Dictionary<string, TestA> to create a map from a "name" to an object... I'm not sure. How do you want to use these names later?

Activator.CreateInstance would usually be appropriate if you don't know the type until execution time. Is that actually the case, or not? What information do you have at compile time, and what do you have only at execution time?

When you say you want to "pass a number of parameters to a default constructor" - what exactly do you mean? Usually the term "default constructor" is used to refer to a parameterless constructor1. How are you intending to pass parameters to a parameterless constructor?


1 I prefer to reserve it for a parameterless constructor created by the compiler when you haven't specified any constructors at all, but there we go.

Jon Skeet
Yes! Use a dictionary. Not reflection. +1
Spencer Ruport
Yeah, I think a Dictionary is the only way he's going to be able to use string names. I suspect he's asking how to implement the solution he's already decided on.
Joel B Fant
1) Sorry, not default constructor, just a constructor.2) Yes, sounds like a dictionary will work.
jw0rd