![](/img/trans.png)
[英]Is it possible create a new instance of a generic type inside the body of a generic method?
[英]Passing a new instance of a Type through a Generic Method
我有一系列非常相似的方法:
private static DocumentBody GetPdfBodyObject(int sectionId)
{
DocumentBody db = new DocumentBody();
// Add some stuff to Db
return db;
}
private static DocumentHeader GetPdfHeaderObject(int sectionId)
{
DocumentHeader dh = new DocumentHeader();
// Add some stuff to DH - similar to above
return dh;
}
等等...
正如您所看到的,这两个示例之间的区别是基于正在实例化和返回的Type。
所以我立刻想到使用通用方法来减少代码重复......我似乎无法弄清楚哪种方式是“最佳实践”,我可以在不使用反射的情况下得到我需要的东西吗?
我没有使用过通用方法,所以欢迎任何建议。
这里的最佳实践是将静态方法重构为工厂方法或使用构建器模式,如果它是您正在构建的更大的对象(看起来就是这种情况)。 泛型方法的使用在这里仅限于无参数构造函数 - 每当构造函数接受参数时,您需要使用Activator,它是反射,您通常不需要这样的代码。 话虽如此:您使用无参数构造函数给出了构造对象的两个方法,因此您可以将两者重构为:
private static TT GetPdfObjectPart<TT>(int sectionId) where TT : class, new()
{
TT dh = new TT();
// Add some stuff to DH - similar to above
return dh;
}
还要注意,正如@dymanoid指出的那样 - 在这种情况下,你只能使用合同的一部分( where子句) - 所以你需要为所有构造的类型实现一些'通用'接口 - 而你' d仅限于界面中的方法。 看起来你在经典情况下使用构建器模式。
至于我,界面很好:
private interface IDocumentPart
{
}
private class DocumentHeader : IDocumentPart
{
}
private class DocumentBody : IDocumentPart
{
}
private static T GetPdfPart<T>(int sectionId) where T : IDocumentPart, new()
{
var doc = new T();
return doc;
}
当然,您可以为接口中的所有类定义一些常用的属性和方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.