简体   繁体   English

指定受约束的通用类是子类?

[英]Specifying that a constrained generic class is a subclass?

I have this class definition: 我有这个类的定义:

public abstract class AbstractListViewModel<T>  : AbstractWorkspaceViewModel

So I have a class called AbstractListViewModel that has a generic type, and that is a subclass of AbstractWorkspaceViewModel . 因此,我有一个名为AbstractListViewModel的类,它具有通用类型,并且是AbstractWorkspaceViewModel的子类。

However, I need to constrain T to only be subclasses of AbstractWorkspaceViewModel . 但是,我需要将T限制为AbstractWorkspaceViewModel子类。 I tried the following: 我尝试了以下方法:

public abstract class AbstractListViewModel<T> where T :
    AbstractWorkspaceViewModel, : AbstractWorkspaceViewModel
public abstract class AbstractListViewModel<T> where T :
    AbstractWorkspaceViewModel : AbstractWorkspaceViewModel

But this syntax is invalid. 但是此语法无效。

So here I am trying to say "A class called AbstractListViewModel that is a subclass of AbstractWorkspaceViewModel and has a generic type that is also a subclass of AbstractWorkspaceViewModel . 所以在这里我想说的“,即A类AbstractListViewModel是的子类AbstractWorkspaceViewModel并有一个通用的类型,这也是的一个子类AbstractWorkspaceViewModel

How do I define this? 我该如何定义?

It's the ordering of your constraint. 这是约束的顺序。 Try this: 尝试这个:

public abstract class AbstractListViewModel<T>  : AbstractWorkspaceViewModel
    where T : AbstractWorkspaceViewModel

You want this: 你要这个:

public abstract class AbstractListViewModel<T> : AbstractWorkspaceViewModel
    where T : AbstractWorkspaceViewModel
public abstract class AbstractListViewModel<T> : AbstractWorkspaceViewModel where T : AbstractWorkspaceViewModel

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

相关问题 在C#中强制约束泛型类 - Casting constrained generic class in C# 将从受约束的泛型基类继承的类分配给受约束的泛型的继承基类 - Assigning class that inherits from a constrained generic base class to the inherited base class with the constrained generic 指定依赖于另一个泛型类的泛型约束 - Specifying a generic constraint that depends on another generic class 在不指定通用类的情况下实现通用接口 - Implementing generic interface without specifying generic class 检查类是否是特定泛型的子类 - Check if class is a subclass of specific generic 将CollectionBase子类转换为通用列表,而无需显式指定类型 - Cast a CollectionBase subclass to a generic List without specifying the type explicitly 使用继承的泛型类型作为类型受限类的方法的输入 - Using an inherited generic type as an input to a method of a type constrained class 如何使用受约束的泛型类型参数将 class 实例化为派生接口 - How to instantiate a class as the interface that it derives from with constrained generic type parameter 如何对通用约束类使用方法隐藏(新) - How to use method hiding (new) with generic constrained class 实例化类型约束的泛型类,而不对其进行子类化 - Instantiating a type-constrained generic class without subclassing it
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM