Is it possible to start with a string and instantiate an object of this string?

I am currently working with LINQ and C #.

I have a DropDownList table in my LINQ to SQL model.

I want the user to be able to select the LINQ table name from DropDown. In the code, I want to instantiate this LINQ class and then run Select or it or something else that I want.

How could I create an object based on what object name in the row the user chose? Am I thinking wrong from the start?

+3
source share
5 answers

You want Type.GetType (string) and Activator. CreateInstance (type) .

, Type.GetType() mscorlib, , . , .

Assembly.GetType(string), Activator.CreateInstance.

( . , , , .)

+6

ASP.NET, , . , , , . factory, ( ).

+3

LINQ-to-SQL ; , db.GetTable. ITable, ITable. , ...

ITable, Type, () Assembly.GetType:

    using (var ctx = new MyDataContext()) {
        string name = "Customer"; // type name
        Type ctxType = ctx.GetType();
        Type type = ctxType.Assembly.GetType(
            ctxType.Namespace + "." + name);
        ITable table = ctx.GetTable(type);
        foreach(var row in table) {
            Console.WriteLine(row); // works best if ToString overridden...
        }
    }

, Type, Activator :

        object newObj = Activator.CreateInstance(type);
        // TODO: set properties (with reflection?)
        table.InsertOnSubmit(newObj);

, :

    using (var ctx = new MyDataContext()) {
        string name = "Customers"; // property name
        ITable table = (ITable) ctx.GetType()
            .GetProperty(name).GetValue(ctx, null);
        foreach (var row in table) {
            Console.WriteLine(row); // works best if ToString overridden...
        }
    }

(Where) .. , Expression . , , ...

+1

: . , "" , .

+1

.

Performing as he suggested, I noticed an extension method Cast<TResult>(defined in System.Linq).

Unfortunately, you cannot use an instance typeto create:

Type dcType = dc.GetType();
Type type = dcType.Assembly.GetType(String.Format("{0}.{1}", dcType.Namespace, name));
var row = dc.GetTable(type).Cast<type>().SingleOrDefault(i => i.ID == 123);
0
source

All Articles