开发者

convert class string to class

I have the code below in my ASP.NET app, I would like to convert converterName variable to Class and pass it to FillRequest<T> method. Is it possible?

var converterName = HttpContext.Current.Items["ConverterName"] as string;
FillRequest<Web2ImageEntity>(Request.Params);

Alternatively I could do

    var converterName = HttpContext.Current.Items["ConverterName"] as string;

if (converterName == "Web2ImageEntity")
    FillRequest<Web2ImageEntity>(Request.Params);

but I have about 20 entity classes and I would like to find a 开发者_如何转开发way to write code as short as possible.


That would not be possible as the generic type needs to be specified at the compile time. What you can do is change the FillRequest method to be something like below and then use reflection to do the desired task

FillRequest(string[] params,Type converter)
{
  //Create object from converter type and call the req method
}

Or make the FillRequest take a Interface

FillRequest(string[] params, IConverter c)
{
 //call c methods to convert
}

Calling this would be something like:

   var type = Type.GetType(converterName);
   FillRequest(Request.Params,(IConverter)Activator.CreateInstance(type));


Yes, take a look at Activator.CreateInstance():

        var converterName = HttpContext.Current.Items["ConverterName"] as string;

        var type = Type.GetType(converterName);
        var yourObject = Activator.CreateInstance(type);

Be aware that the type must have a public parameterless constructor. Here is a link to the MSDN documentation; there are a bunch of overloads which might be useful to you:

http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx

UPDATE: If you must pass the object to a method with a generic type, then you will run into problems because the type is not known at compile time. In that case, I would consider having all of your converters implement a common interface, something like this:

var converterName = HttpContext.Current.Items["ConverterName"] as string;

var type = Type.GetType(converterName);
var yourObject = Activator.CreateInstance(type) as IMyConverter;
if (yourObject != null)
    FillRequest<IMyConverter>(yourObject);


I found code idea here. Peter Moris pointed that he took code from Jon Skeets book, so if it will be useful - high five to Jon :)

create method:

public void DoFillRequest(Type type, string[] params)
{
   MethodInfo methodInfo = this.GetType().GetMethod("FillRequest");
   MethodInfo genericMethodInfo = methodInfo.MakeGenericMethod(new Type[]{ type });
   genericMethodInfo.Invoke(this, new object[]{ params });
}

and now call it:

var type = Type.GetType(converterName);
DoFillRequest(type, Request.Params);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜