Home > Enterprise >  C# generic bounds
C# generic bounds

Time:05-18

I have a abstract dto class,I want to write a batch class to deal the derived dto:

dto:

public abstract class Command
    {
        private string TraceNo { get; set; }

        public override string ToString()
        {
            return ObjectDumper.Dump(this);
        }
    }

derived dto:

 public class UserLoginDirectlyCommand : Command
    {
        public List<string>? LoginUserId { get; set; }
        public int ReserveCount { get; set; }
    }

interface:

public interface ICommandHandler<in T> where T : Command
{
    void Handler(T command, byte[] attachment);
}

concrete handler:

public class LoginDirectlyCommandHandler : ICommandHandler<UserLoginDirectlyCommand>
{
    public void Handler(UserLoginDirectlyCommand command, byte[] attachment)
    {
    }
}

I want to get a dictionary with key is command id and value is concrete handler:

public static Dictionary<int, T> GetCommandHandler<T, TC>() where TC : Command where T : ICommandHandler<TC>
    {
       List<ICommandHandler<Command>> list;
       var dic = new Dictionary<int, T>();
       dic[2] = new LoginDirectlyCommandHandler();

       return dic;
    }

but the statement dic[2] = new LoginDirectlyCommandHandler(); cannot compile:Cannot convert source type 'LoginDirectlyCommandHandler' to target type 'T'

Could anyone tell me how to pass the compile? thx!

CodePudding user response:

Okay... so now we have this method:

 public static Dictionary<int, T> GetCommandHandler<T, TC>() where TC : Command where T : ICommandHandler<TC>
    {
        List<ICommandHandler<Command>> list;
        var dic = new Dictionary<int, T>();
        dic[2] = new LoginDirectlyCommandHandler();

        return dic;
    }

How would you call that method?

Like this?

GetCommandHandler<Something that extends ICommandHandler, somethign that extends Command>()...

So now when the dictionary is instantiated it will instatiate it with that concrete type.

Thus when you to the assignment to LoginDirectlyCommandHandler it cannot guarantee that the concrete types provided will be compatible with the assignment taking place. The concrete type you provided could be anything (as long as they subclass Command and ICommandHandler respectively). Thus there is no guarantee that those types will be compatible with your assignment of LoginDirectlyCommandHandler.

  • Related