Property in base base class with various implementations

I have an abstract class CommandBase<T, X> that I want to have an InnerCommand property.

But since InnerCommand can have different types for T and X than the command containing it, how can I determine this?

Abstract class:

 public abstract class CommandBase<T, X> where T : CommandResultBase where X : CommandBase<T, X> { public CommandBase<T, X> InnerCommand { get; set; } (...) } 

In the above example, InnerCommand will only accept instances with the same types for T and X, but I need to allow other types.

AddOrderitemCommand:

 public class AddOrderitemCommand : CommandBase<AddOrderitemResult, AddOrderitemCommand> { (...) } 

May contain WebserviceCommand:

 public class GetMenuCommand : CommandBase<GetMenuResult,GetMenuCommand> { (...) } 

Please provide syntax to allow this.

+4
source share
2 answers

Basically you have three options:

  • Use dynamic as the type of this property. I wouldn’t do anything.
  • Use object as the type of this property. I wouldn’t do anything.
  • Create a non-core base class or interface for commands. Make CommandBase<T, X> implement it and use as property type. The way I go.
+6
source

If InnerCommand does not belong to the parent T / X , I would suggest using a non-generic InnerCommand that does not advertise the type in the signature. This may mean adding a non-generic base type ( CommandBase ) or an interface ( ICommandBase ). Then you can simply use:

 public ICommandBase InnerCommand {get;set;} // note : CommandBase<T,X> : ICommandBase 

or

 public CommandBase InnerCommand {get;set;} // note : CommandBase<T,X> : CommandBase 
+5
source

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


All Articles