简体   繁体   English

在C#中将对象转换为通用对象

[英]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>". 这些对象的类型均为“ XmlRepository <T>”或“ 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>: 我也知道哪种类型的参数应该返回XmlRepository <T>或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. 因为不允许我提供变量作为泛型类型参数...此示例在某种程度上已经简化了,所以我无法用专用的Type本身替换类型变量(xmlTypeVar)。

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 <>的Method,最好的方法是创建一个非通用基类并在其中调用该方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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