比较基类中的类型

本文关键字:类型 基类 比较 | 更新日期: 2023-09-27 18:30:30

我有一个Part基类

class Part {
    public PartType Type { get; set; }
}

有许多实现。

class Wire : Part {   }

我的程序中有一个树视图。当我单击其中的某个元素时,我希望一个列表填充我在树视图中单击的所有类型部分。

当我打开多个列表时,我只希望那些列表加载与我在树视图中单击的具有相同 PartType 的零件。

class BasePartListViewModel<T> : ListViewModel where T : Part {
    protected override void OnTreeSelectionChanged(PartType type)
        if (type == PartType.Wire) {
            //load the Wires from the DB and display them
        } 
        else {
            //ignore the changed type event
        }
    }
}

但是由于这是使用 T 的所有零件的基类,我想替换

if (_type == PartTypeEnum.Wire)

用类似的东西

if (_type == T.Type)

但这当然行不通。不然呢?

比较基类中的类型

由于部件类型在设计上是类类型的静态信息(我说得对吗?),您可以使用属性来存储它:

[AttributeUsage(AttributeTargets.Class)]
public class PartTypeAttribute : Attribute
{
    public readonly PartType PartType;
    public PartTypeAttribute(PartType partType)
    {
        PartType = partType;
    }
}

然后将其应用于后代类:

[PartType(PartType.Wire)]
class Wire : Part
{
}

然后在 BasePartListViewModel 类的静态构造函数中,您可以观察相应的值:

class BasePartListViewModel<T> : ListViewModel
    where T : Part
{
    private static PartType PartTypeOfT;
    static BasePartListViewModel()
    {
        var attr = typeof(T).GetCustomAttributes(typeof(PartTypeAttribute), true)
            .FirstOrDefault() as PartTypeAttribute;
        if (attr != null)
            PartTypeOfT = attr.PartType;
    }
    protected override void OnTreeSelectionChanged(PartType type)
    {
        if (type == PartTypeOfT) {
            ....
        }
    }
}

如果你这样做。GetType() 它将返回为 BasePartListViewModel'1[Wire]

理想情况下,您不应该在基类中引用它。