I have two similar classes A and B, which contain the following code:
//A or B depending on class
public class LogicA
{
public List<Members> MembersA { get; set; } = new List<Member>();
public void AddMember(Member member)
{
MembersA.Add(member);
}
public List<Member> GetResultA()
{
return MembersA;
}
}
I want to use the MembersA and MembersB lists in another class (say logicC). I have seen similar questions and they mostly involve single inheritance. The process I thought to use was to create instance of lists from two different classes in the third class through multiple inheritance but in C#, only interface support multiple inheritance and I am using classes, hence my issue.
CodePudding user response:
Is there any reason that you need to use inheritance only?
Generally, the way of using a member of Class is follow
class logicC
{
static void Main(string[] args)
{
LogicA logicA = new LogicA();
LogicB logicB = new LogicB();
List<Member> memberA = logicA.memberA;
List<Member> memberB = logicB.memberB;
}
}
CodePudding user response:
Both Logica.GetResultA
and presumably LogicB.GetResultB
return List<Member>
. So there is no problem
LogicC can be
class LogicC{
void NoodleOnList(List<Member> input){
....
}
}
then
LogicC lc;
lc.NoodelOnList(la.GetMembersA());
lc.NoodelOnList(lb.GetMembersb());
CodePudding user response:
Well, you should re-consider your design choices and think about how to make your code less prone to change.
You can create a new class to aggregate Lists from A, B. And via Composition this new class might access Lists from other inner objects.
public class logicC {
public LogicA logicA;
public LogicB logicB;
public List<Member> GetResultC() => logicA.GetResultA().Concat(logicB.GetResultB());
}
CodePudding user response:
you can use static
modifier for your methods for example:
public static class LogicA
{
public static List<Members> MembersA { get; set; } = new List<Member>();
public static void AddMember(Member member)
{
MembersA.Add(member);
}
public static List<Member> GetResultA()
{
return MembersA;
}
}
and use this like that:
using.YourProject;
public class LogicC
{
Members members = new();
List<Members> membersList = new();
LogicA.AddMember(member);
membersList = LogicA.GetResult();
}