简体   繁体   中英

Convert object to generic object in C#

I have a list of generic objects:

private readonly List<object> _repositories = new List<object>();

Those object are all of type either "XmlRepository<T>" or "DbRepository<T>". I also have a generic Methods that returns me the first repository of generic type argument provided:

public IRepository<T> GetRepository<T>() where T : class {...}

I do also know what type argument should return XmlRepository<T> or DbRepository<T>:

var xmlTypeVar = typeof(XmlType);
var myXmlRepo = GetRepository<xmlTypeVar>()

but I don't know how to to convert it to the correctly typed object instance...

var myConvertedXmlRepo = myXmlRepo as XmlRepository<???>

What do I have to do here? The following is not possible:

var myConvertedXmlRepo = myXmlRepo as XmlRepository<xmlTypeVar>
since I'm not allowed to provide a variable as generic type argument... This example here is somehow simplicated, so it is not possible to me to replace the type variable (xmlTypeVar) with the dedicated Type itself.

Any help is highly appreciated! Thank you very much!

use reflection to create a generic type without knowing at compile time:

Type genericXmlRepositoryType= typeof(XmlRepository<>);
Type[] typeArgs = new[] { xmlTypeVar };
var generic = genericXmlRepositoryType.MakeGenericType(typeArgs);

As written in the comments, if you want to access a Method of XmlRepository<> after creating the dynamic instance, the best idea is to create a non-generic base class and call the method there:

XmlRepository repository = (XmlRepository)generic;
repository.UseTypeSpecificMethod();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM