将类字符串转换为类
本文关键字:转换 字符串 | 更新日期: 2023-09-27 18:07:15
我有下面的代码在我的ASP。. NET应用程序,我想将converterName
变量转换为类并将其传递给FillRequest<T>
方法。这可能吗?
var converterName = HttpContext.Current.Items["ConverterName"] as string;
FillRequest<Web2ImageEntity>(Request.Params);
或者我也可以写
var converterName = HttpContext.Current.Items["ConverterName"] as string;
if (converterName == "Web2ImageEntity")
FillRequest<Web2ImageEntity>(Request.Params);
但是我有大约20个实体类,我想找到一种方法来编写代码尽可能短。
这是不可能的,因为泛型类型需要在编译时指定。你能做的是改变FillRequest方法如下所示,然后使用反射来执行所需的任务
FillRequest(string[] params,Type converter)
{
//Create object from converter type and call the req method
}
或者让FillRequest接受一个接口
FillRequest(string[] params, IConverter c)
{
//call c methods to convert
}
调用它会像这样:
var type = Type.GetType(converterName);
FillRequest(Request.Params,(IConverter)Activator.CreateInstance(type));
是的,看看Activator.CreateInstance():
var converterName = HttpContext.Current.Items["ConverterName"] as string;
var type = Type.GetType(converterName);
var yourObject = Activator.CreateInstance(type);
请注意,该类型必须有一个公共无参数构造函数。这里是MSDN文档的链接;这里有一堆可能对你有用的重载:
http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspxUPDATE:如果必须将对象传递给泛型类型的方法,则会遇到问题,因为编译时不知道该类型。在这种情况下,我会考虑让所有的转换器实现一个公共接口,就像这样:
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);
我在这里找到了代码的想法。Peter Moris指出,他从Jon Skeets的书中获得了代码,所以如果它有用的话-向Jon击掌:)
创建方法:
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 });
}
现在叫它:
var type = Type.GetType(converterName);
DoFillRequest(type, Request.Params);