我有一个函数,我想使用泛型返回 CreditSupplementTradeline 或 CreditTradeline。问题是如果我创建一个 T ctl = new T(); ...我无法对 ctl 进行操作,因为 VS2010 无法识别其任何属性。这可以做到吗?谢谢。
internal T GetCreditTradeLine<T>(XElement liability, string creditReportID) where T: new()
{
T ctl = new T();
ctl.CreditorName = this.GetAttributeValue(liability.Element("_CREDITOR"), "_Name");
ctl.CreditLiabilityID = this.GetAttributeValue(liability, "CreditLiabilityID");
ctl.BorrowerID = this.GetAttributeValue(liability, "BorrowerID");
return ctl;
}
我收到这个错误:
Error 8 'T' does not contain a definition for 'CreditorName' and no extension method 'CreditorName' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?)
最佳答案
你需要有一个具有适当属性的接口(interface),例如这样的东西:
internal interface ICreditTradeline
{
string CreditorName { get; set; }
string CreditLiabilityID { get; set; }
string BorrowerID { get; set; }
}
在您的方法中,您需要向 T
添加一个约束,要求它必须实现上述接口(interface):
where T: ICreditTradeline, new()
你的两个类应该实现接口(interface):
class CreditTradeline : ICreditTradeline
{
// etc...
}
class CreditSupplementTradeline : ICreditTradeline
{
// etc...
}
然后你可以调用这个类作为你的类型参数的方法:
CreditTradeline result = this.GetCreditTradeLine<CreditTradeline>(xElement, s);
关于c# - 如何实例化、操作和返回Type T,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12846115/