How to create, manage and return type T

I have a function that I would like to return to CreditSupplementTradeline or CreditTradeline using generics. The problem is that if I create T ctl = new T (); ... I cannot work on ctl because VS2010 does not recognize any of its properties. It can be done? Thanks.

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; } 

I get this error:

Error 8 'T' does not contain a definition for 'CreditorName' and no the extension method 'CreditorName' that takes the first argument of type 'T' (if you did not specify a directive or assembly link?)

+4
source share
2 answers

You should have an interface with the appropriate properties, for example, something like this:

 internal interface ICreditTradeline { string CreditorName { get; set; } string CreditLiabilityID { get; set; } string BorrowerID { get; set; } } 

In your method, you need to add a restriction on T , requiring it to implement the interface:

 where T: ICreditTradeline, new() 

Your two classes should implement the interface:

 class CreditTradeline : ICreditTradeline { // etc... } class CreditSupplementTradeline : ICreditTradeline { // etc... } 

Then you can call the method with the class as a parameter of your type:

 CreditTradeline result = this.GetCreditTradeLine<CreditTradeline>(xElement, s); 
+14
source

Right now, your program just knows that T is at least an object that has a constructor without parameters. You need to update where T to include an interface constraint that tells your function that T is a member of some interface that contains a definition for CreditorName , CreditLiabilityID and BorrowerID . You can do it like this:

 where T: InterfaceName, new() 
+9
source

Source: https://habr.com/ru/post/1439232/


All Articles