mercredi 26 juillet 2017

C# Resolving Base Class to Correct Repository Method Call Based on Implemented Type

In our current project, we have an abstract base user class that is implemented by multiple other user types. We have a comparison class that can compare any of these types and then needs to call a correct update api based on the implemented type. I am trying to avoid bringing an if(typeof(User)) logic tree into the code and was hoping to figure out some way to solve the issue with method overloading. Are there any design patterns that can help solve this issue with some type of interface that can be dependency injected? Here is a basic code example

using System;
using System.Collections.Generic;

namespace ConsoleApplication5
{
    class Program
    {
        static void Main(string[] args)
        {
            List<BaseUser> TestUsers = new List<BaseUser>();
            TestUsers.Add(new UserA() { Email = "test1@test.com", Location = "New York, NY" });
            TestUsers.Add(new UserB() { Email = "test2@test.com", State = "TN" });

            foreach (var user in TestUsers)
            {
                //need to invoke the correct Print repo method based on the actual user type
                dynamic u = user;
                u.Print();
            }

            Console.Read();
        }
    }

    public abstract class BaseUser
    {
        public string Email { get; set; }
    }

    public class UserA : BaseUser
    {
        public string Location { get; set; }
    }
    public class UserB : BaseUser
    {
        public string State { get; set; }
    }

    public class UserARepo
    {
        void Print(UserA user)
        {
            Console.Write($"User A Saved {user.Email}, {user.Location}");
        }
    }
    public class UserBRepo
    {
        void Print(UserB user)
        {
            Console.Write($"User B Saved {user.Email}, {user.State}");
        }
    }

}

Aucun commentaire:

Enregistrer un commentaire