c# - 如何实例化、操作和返回Type T

标签 c# generics

我有一个函数,我想使用泛型返回 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/

相关文章:

C# 培训测验

c# - 获取对象实例上自定义属性的*值*?

java - 遍历对象类型的泛型列表

delphi - 如何判断非对象泛型的类型?

c# - 是否可以在引入其他泛型类型的泛型类上使用构造函数?

c# - 删除 block 的内容缩进

c# - 如何让事件向事件处理程序发送参数?

c# - C#切换用户控件时暂停视频或停止Web浏览器

swift - 在泛型类中传递泛型参数

java - 为什么我们有 contains(Object o) 而不是 contains(E e)?