简体   繁体   中英

Generic <T> and 2 base class inheritance

I have a question and am getting a little stumped on this one. It's probably easy but I'm just missing it.

If I have a class what contains necessary structures and the structures can inherit. I need a generic method what that an be passed to and then used. For example, let's say I have a structure Test, Test-A which inherits from Test. Then I have a MyTest and MyTest-B both which inherit from Test-A.

How can I create a method using T so that I can supply both MyTest and MyTest-B and I can use either of them in the method?

So:

public class Test
{
    public int Hello {get; set; }
}

pubilc class Test-A : Test
{  
   public string Name { get; set; }
}

public class MyTest : Test-A
{
   public string Last { get; set; } 
}

public class MYTest-B : Test-A
{
   public int Age {get; set; }
}

I need a method like:

private void MyList<T>(List<T> TestList) where T : **{not sure what this would be}**
{
    TestList.Age = 10;

    **OR** 

    TestList.Name = "Jane";
}

How or what am I missing (or not understanding) to be able to do that?

Any assistance would be greatly appreciated.

There is no constraint you could use which would match both of those conditions. The only way to handle this would be to use two, overloaded methods, as there is no shared contract.

Generic constraints only work if there is a base class or interface shared which all types implement, and use the same contract (ie: both have Name and Age properties).

How can I create a method using T so that I can supply both MyTest and MyTest-B and I can use either of them in the method?

     **TestList.Age = 10;**

     ...

How would this work if you passed in an object of type MyTest , given that MyTest doesn't have an Age property?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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