开发者

Convert string parameter to object type

Consider the following code:

public ActionResult GenericActionForSomething(string objectType)
    {
        switch (objectType)
        {
            case 开发者_开发知识库"Business":
                // Do Something with object here, like save
                _db.Create<Business>();
                break;
        }

        return View();
    }

How can I convert a string parameter to an object? For this example I need to convert the parameter "objectType" into an object of type "Business". Any ideas would be greatly appreciated.


You can instantiate an object based on its type name by using Activator.CreateInstance. For that particular overload of the method you need to supply the assembly name as well; for this you may find useful the Assembly class' GetExecutingAssembly and GetCallingAssembly methods.


There's no one single way to do this. If your Business class has a constructor which accepts string, you can invoke that. If it has an explicit conversion operator, you can use it as well. If it has an associated TypeConverter, use that too.

Your question is way too broad.


I'm thinking that you might be wanting to do model binding to your action, like:

public ViewResult NewBusiness(Business business)
{
    _db.Create<Business>(business);
    return View();
}

Read a general overview of model binding in this article.


You need to use reflection to achieve this. You can either use Activator.CreateInstance(className) method or you can first load the Assemply containing your type and then call CreateInstance() method like this:

Assembly assem = Assembly.Load(assemblyName);
Object obj = assem.CreateInstance(className);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜