lundi 15 mars 2021

Passing dynamic class parameter at runtime - is it possible? [duplicate]

It was suggested I review this URL Pass An Instantiated System.Type as a Type Parameter for a Generic Class, and although it's similar, it is not the same - I'm not looking for an instance of a class to be passed to a consumer, but instead the definition of a class.

I'm working with an example I found online, and am trying to dynamically pass a class reference to its class with the following signature:

public class DataNamesMapper<TEntity> where TEntity : class, new()

A simple test, I can instantiate the DataNamesMapper class using this class:

public class Testing { }

with a simple call like:

var mapper1 = new DataNamesMapper<Testing>();
  • Success!

But at runtime, I want to dynamically pass a class to DataNamesMapper without directly referencing the class. This doesn't work:

Type testing = typeof(Testing);
var mapper2 = new DataNamesMapper<testing>();
  • 'testing' is a variable but is used like a type

In my case, I'm looping through a set of table names and using the TableName, want a reference to the class object/definition per below:

Dictionary<string, Type> dict = new Dictionary<string, Type>
{
  { "Schedules", typeof(Schedules) }
};
foreach (DataTable tbl in dsMira.Tables)
{
  Type myType = dict[tbl.TableName];
  var mapper3 = new DataNamesMapper<myType>();

  var classString = $"myNamespace.{tbl.TableName}";
  var objectType = Type.GetType(classString);
  var instantiatedObject = Activator.CreateInstance(objectType);
  var mapper4 = new DataNamesMapper<instantiatedObject>();
}

"mapper3" instance fails because it's just a rework of the "mapper2" approach.

  • 'myType' is a variable but is used like a type

and the "mapper4" approach I don't believe will ever work because the DataNamesMapper isn't expecting an instantiated object. Regardless, the error message is same:

  • 'instantiatedObject' is a variable but is used like a type

Is it possible to dynamically pass a class at runtime?





Aucun commentaire:

Enregistrer un commentaire