简体   繁体   English

具有不同实现的泛型基类中的属性

[英]Property in generic base class with different implementation

I've got an abstract class CommandBase<T, X> that I want to have a property InnerCommand . 我有一个抽象类CommandBase<T, X> ,我希望有一个属性InnerCommand

But since the InnerCommand might have other types for T and X than the command that contains it, how can I define that? 但由于InnerCommand可能包含T和X的其他类型而不是包含它的命令,我该如何定义?

The 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 example above InnerCommand will only accept instances that have the same types for T and X, but I need to allow for other types. 在上面的示例中, InnerCommand只接受T和X具有相同类型的实例,但我需要允许其他类型。

An AddOrderitemCommand: AddOrderitemCommand:

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

Might contain a WebserviceCommand: 可能包含WebserviceCommand:

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

Please advise on the syntax for allowing this. 请告知允许此语法的语法。

You basically have three options: 你基本上有三个选择:

  1. Use dynamic as the type of that property. 使用dynamic作为该属性的类型。 Nothing I would do. 我什么都做不了。
  2. Use object as the type of that property. 使用object作为该属性的类型。 Nothing I would do. 我什么都做不了。
  3. Create a non-generic base class or interface for commands. 为命令创建非泛型基类或接口。 Make CommandBase<T, X> implement it and use it as the type of the property. 使CommandBase<T, X>实现它并将其用作属性的类型。 That's the way I would go. 这就是我要去的方式。

If the InnerCommand doesn't relate to the parent T / X , then I would suggest using a non-generic InnerCommand that doesn't advertise the type in the signature. 如果InnerCommand与父T / X InnerCommand ,那么我建议使用不通用签名类型的非泛型InnerCommand This may mean adding a non-generic base-type ( CommandBase ) or an interface ( ICommandBase ). 这可能意味着添加非泛型基类型( CommandBase )或接口( 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM