Overloading and calling functions automatically by lowering the parameter value

I have a base class User .

I have 2 derived classes from a user called DerivedUser, OtherDerivedUser

I have the following code:

 User user = newUser.CreateUserByType();
 SendNewUser(user); 

I don't want to execute an if or switch statement , and then do downcast for derived types.

I just want to make a single line call.

 SendNewUser(user);

I want ** clean single-layer code *.

This method, according to its type, will dynamically “know” which method to call.

I have 2 functions called SendNewUser that are overloaded with a derived type.

Is there a way to call the correct function by downcasting to the right derived class (I don't want to explicitly throw)

   private static void SendNewUser(DerivedUser user){
       ...
      }

     private static void SendNewUser(OtherDerivedUser user){
       ...
      }
+4
3

, # 7:

switch (user)
{
    case DerivedUser u:
        SendNewUser(u);
        break;
    case OtherDerivedUser u:
        SendNewUser(u);
        break;
    default:
        throw new InvalidOperationException("Where did that come from?");
}

if, :

if (user is DerivedUser u) {
    SendNewUser(u);
}
else if (user is OtherDerivedUser u) {
    SendNewUser(u);
}
else {
    throw new InvalidOperationException("Where did that come from?");
}
+3

, .

:

  • SendNewUser DerivedUser OtherDerivedUser. , , user.SendNewUser().

  • :

    public void SendNewUser(User user)
    {
        if (user is DerivedUser)
        {
            SendNewUserInternal((DerivedUser)user);
        }
        else if (user is OtherDerivedUser)
        {
            SendNewUserInternal((OtherDerivedUser)user);
        }
        else
        {
            throw new InvalidArgumentException("Wrong user type.");
        }
    }
    

, , . 1, .

+3

if switch, downcast .

dynamic :

User user = newUser.CreateUserByType();
SendNewUser((dynamic)user); 

:

public class Program
{
    public static void Main()
    {
        Base ba = new A();
        Do((dynamic)ba);
        ba = new B();
        Do((dynamic)ba);
    }

    public static void Do(A a)
    {
        System.Console.Write("A");
    }

    public static void Do(B b)
    {
        System.Console.Write("B");
    }
}

public class Base{}
public class A : Base{}
public class B : Base{}

:

AB
+3

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


All Articles