简体   繁体   中英

Understanding a type assigning when using generics methods/types

I'm trying to build a generic type that will accept when initializing an instance of type T1 and accept an instance of type T2 in its methods.

So, now I have a generic method, where acceptable types have a convention - to be a child of some abstract class, and I have internal collection of this abstract type instances:

private readonly IList<Tuple<CommandBase<SocialNetworkUnit, SocialNetworkUnit>, SocialNetworkUnit>> _history;

public bool Invoke<TInitiator, TParameter>(CommandBase<TInitiator, TParameter> command, TParameter parameter)
    where TInitiator : SocialNetworkUnit
    where TParameter : SocialNetworkUnit
{
    var success = command.Run(parameter);
    this._history.Add(new Tuple<CommandBase<SocialNetworkUnit, SocialNetworkUnit>, SocialNetworkUnit>(command, parameter));
}

But I have a compilation error said that TInitiator- and TParameter- parameters (conventioned to SocialNetworkUnit) cannot be used for collection.

Argument 1: cannot convert from 'CommandUnits.CommandBase<TInitiator,TParameter>' to 'CommandUnits.CommandBase<Command.SNUnit.SocialNetworkUnit,Command.SNUnit.SocialNetworkUnit>'

Can you show me my mistake?

Thanks

CommandBase isn't covariant with respect to these two generic arguments. It would need to be covariant for that to work, and in C# classes cannot be covariant, only interfaces can be. If you create an interface that has both of these generic arguments as being covariant, and use that interface instead of CommandBase in the list that you have, then the code would be able to work.

尝试显式强制转换:

this._history.Add(new Tuple<CommandBase<SocialNetworkUnit, SocialNetworkUnit>, SocialNetworkUnit>(command as CommandBase<SocialNetworkUnit, SocialNetworkUnit>, parameter));

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