简体   繁体   中英

Declaring an object when type is “unknown”

Here is my problem:

I have the function

public static void fillObject(object [] obs, DataTable dt)
{
    for (int j = 0; j < dt.Rows.Count; j++)
    {
        DataRow dr = dt.Rows[j];
        fillObject(obs[j], dr);
    }
}

obs is an array of some type of class (let say for the example "sheep") when I debug I get that obs[j] is a null and not an object type of sheep so I need to do something like

obs[j] = new sheep();

any ideas?

If you want to strongly type your solution, you can use generics

public static void FillObject<T>(T [] obs, DataTable dt) where T: new
{
    //...

    obs[j] = new T();
}

You would then call the function like

FillObject<Sheep>(mySheep, dt);

It's hard to tell exactly what you mean; depending on the specific scenario, you could do one of the following:

You can pass a construction function to the method:

public static void fillObject(object [] obs, DataTable dt, Func<object> builder)
{
   for (int j = 0; j < dt.Rows.Count; j++)
   {
      DataRow dr = dt.Rows[j];

      if (obs[j] == null)
         obs[j] = builder();

      fillObject(obs[j], dr);
   }
}

Or if you know the type, you can use a dictionary of construction functions:

Dictionary<Type, Func<object>> sBuilders = new Dictionary<Type, Func<object>>
{
   { typeof(Type1), () => new Type1() },
   { typeof(Type2), () => new Type2() },
   // etc...
};

public static void fillObject(object [] obs, DataTable dt, Type pType)
{
   for (int j = 0; j < dt.Rows.Count; j++)
   {
      DataRow dr = dt.Rows[j];

      if (obs[j] == null)
         obs[j] = sBuilders[pType]();

      fillObject(obs[j], dr);
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM