开发者

Upgraded FileHelpers library and now my code is obsolete

开发者 https://www.devze.com 2023-01-25 16:44 出处:网络
I use reflection to specify the class name dynamically when I do file imports using FileHelpers like this ...

I use reflection to specify the class name dynamically when I do file imports using FileHelpers like this ...

Assembly assembly = Assembly.GetExecutingAssembly();
AssemblyName assemblyName = assembly.GetName();
Type t = assembly.GetType(assemblyName.Name + ".FileDefinitions." + className);
FileHelperEngine engine = new FileHelperEngine(t);

After getting the latest version of the library what I was doing above now considere开发者_高级运维d "obsolete"

The implementation has been changed to generics in this manner

FileHelperEngine<myImportDefinitionClass> = new
                                 FileHelperEngine<myImportDefinitionClass>();

but I am not sure how to specify the myImportDefintionClass dynamically at runtime, using the original reflection code doesn't work.

UPDATE : After trying Paul's code I would now need to be able to do access the methods or whatever within the FileHelpers class such as (this part doesn't compile)

fileHelperEngine.ErrorManager.ErrorMode = ErrorMode.SaveAndContinue;

importData = fileHelperEngine.ReadFileAsDT(filepath);

But I am not real clear about what is actually going on. Any links to better understand the generics concepts would be appreciated also.


Assembly assembly = Assembly.GetExecutingAssembly();
AssemblyName assemblyName = assembly.GetName();
Type emptyGenericType = typeof(FileHelperEngine<>);
Type genericTypeArgument = assembly.GetType(assemblyName.Name + ".FileDefinitions." + className);
Type completeGenericType = emptyGenericType.MakeGenericType(genericTypeArgument);
var fileHelperEngine = Activator.CreateInstance(completeGenericType);

Unfortunately, it is not possible to the cast the resulting object directly to the generic type, c# does not implement duck typing.

I suppose you have two options, use an interface or base class and cast to that, fileHelperEngine does not implement any interfaces, nor does it base class have any useful methods, so that isn't useful. You could change the code and implement one if the licence permits.

The other option is to test the type, this is hacky, but ok if the list of possibilities is small, eg:

if (fileHelperEngine is FileHelperEngine<string>)
    fileHelperEngine = fileHelperEngine as FileHelperEngine<string>;

etc


Breadtruck

I commited the changes with the [Obsolote] attribute yesterday, in fact was to check some examples of the lib for the next release, but are removed now.

You can do an SVN update and recompile it to avoid the warning, sorry for the problems :(

Marcos

0

精彩评论

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

关注公众号