The question is - how to define fields for a class object from a dynamically loaded library? How to load dynamically dll, create a class object and call the object method I found, but what about the properties of the object?

SQLite example:

Assembly a = Assembly.Load("System.Data.SQLite"); object obj = a.CreateInstance("System.Data.SQLite.SQLiteConnection"); 

In runtime, the program knows that the obj object is an object of the SQLiteConnection class SQLiteConnection but not earlier. How do I assign a value to the ConnectionString field? How to set the properties of this class value?

PS - to a particular SQLite question the relationship is not, the technology itself is interested.

UPD: how to add the property figured out, thanks to the link of the dismissed @Igor:

 obj.GetType().GetProperty("ConnectionString").SetValue(obj, "ConStr"); 

However, another question arose - going back to the same SQLite, I will try to assign a connection object for the command object:

 sq_command.GetType().GetProperty("Connection").SetValue(sq_command, obj); 

To which I get an exception:

Ambiguous match detected

How to deal with this?

Stacktrace

in System.RuntimeType.GetPropertyImpl (String name, BindingFlags bindingAttr, Binder binder, Type returnType, Type [] types, ParameterModifier [] modifiers)

in System.Type.GetProperty (String name)

in ConsoleApplication1.Program.Main (String [] args) in C: \ Users \ ... Program.cs: string 68 "string

  • @Igor updated the question - Sergey
  • one
    need to understand: break the chain of calls into separate commands with intermediate variables to find out which of the calls leads to an error - Igor
  • one
    Yes, and complete StackTrace exceptions, please add to the question - Igor
  • @Igor added StackTrace - Sergey

1 answer 1

The question was solved much easier - thanks to such wonderful entities as C # interfaces. It is enough just to explicitly cast objects to the IDbConnection and IDbDataAdapter :

 using (var sq_connection = (IDbConnection)a.CreateInstance("System.Data.SQLite.SQLiteConnection")) { sq_connection.ConnectionString = ConnectionString; using (var sq_command = sq_connection.CreateCommand()) { sq_command.CommandText = sql; sq_command.Connection = sq_connection; var sql_adapter = (IDbDataAdapter)a.CreateInstance("System.Data.SQLite.SQLiteDataAdapter"); sql_adapter.SelectCommand = sq_command; sql_adapter.Fill(DB); } }