开发者

c# Convert variable value to object

开发者 https://www.devze.com 2023-02-07 02:15 出处:网络
I开发者_如何学Go need a way to convert the value of a variable into an object. Lets assume a variable

I开发者_如何学Go need a way to convert the value of a variable into an object.

Lets assume a variable

string viewName = "taDataView";

I need a way to convert the value of variable into something like this:

taDataView viewModel = Container.Resolve<taDataView>();

Something like eval() in php...

Thanks for your help.


One option is to use Unity's Named Registrations (see Resolving an Object by Type and Registration Name in the Unity 2.0 help file). You would still need to know the base type (generally an interface).

// Create container and register types
var myContainer = new UnityContainer();
myContainer.RegisterType<IMyService, DataService>("Data");
myContainer.RegisterType<IMyService, LoggingService>("Logging");

// Retrieve an instance of each type
var myDataService = myContainer.Resolve<IMyService>("Data");
var myLoggingService = myContainer.Resolve<IMyService>("Logging");

Alternatively, see Create an object knowing only the class name (especially Marc Gravell's answer).

EDIT: Revised the example to use generics.

0

精彩评论

暂无评论...
验证码 换一张
取 消