繁体   English   中英

创建基类的集合,然后在集合项中访问派生类的属性

[英]Creating a collection of base class, then access properties of derived classes in the collection items

我有这样的课程

class Base
{
    int Id { get; set; }
}

class Derived1 : Base
{
    string DerivedProperty1 { get; set; }
}

class Derived2 : Base
{
    string DerivedProperty2 { get; set; }
}

现在我有一个这样的收藏课

public class MyCollection    
{
    List<Base> items;

    public void Add(Base baseItem)
    {
         // if baseItem is Derived1, if items contain an item of type Derived1 and has the same DerivedProperty1 value as baseItem, throw exception
         // if baseItem is Derived2, if items contain an item of type Derived2 and has the same DerivedProperty2 value as baseItem, throw exception
         items.Add(baseItem);
    }
}

我认为先检查baseItem的类型然后进行转换不是一种很好的做法,对吗? 否则,您如何建议我解决此设计问题?

根据您的代码和注释,正确的方法是为Base提供IsDuplicateOf方法,并在派生类中重写此方法。 像这样:

class Base
{
    int Id { get; set; }
    public virtual bool IsDuplicateOf(Base other)
    {
        return other != null && Id == other.Id;
    }
}

class Derived1 : Base
{
    string DerivedProperty1 { get; set; }

    public override bool IsDuplicateOf(Base other)
    {
        return IsDuplicateOf(other as Derived1);
    }

    private bool IsDuplicateOf(Derived1 other)
    {
        return other != null && DerivedProperty1 == other.DerivedProperty1;
    }
}

class Derived2 : Base
{
    string DerivedProperty2 { get; set; }

    public override bool IsDuplicateOf(Base other)
    {
        return IsDuplicateOf(other as Derived2);
    }

    private bool IsDuplicateOf(Derived2 other)
    {
        return other != null && DerivedProperty2 == other.DerivedProperty2;
    }
}

您可以在Add方法中使用该方法:

public void Add(Base baseItem)
{
     if(items.Any(x => baseItem.IsDuplicateOf(x)))
         throw new DuplicateItemException(...);

     items.Add(baseItem);
}

但是请注意,如果列表中有很多项并且IsDuplicateOf的代码变得更加复杂,则此方法可能会变慢。

如果不先转换为派生类,就无法从基类访问派生类属性。 但是,根据您的情况,您可以做些不同的事情-代替当前的Add方法(将Base实例作为参数),创建几个Add方法重载,每个派生类重载一个:

public void Add(Derived1 item)
{
    if(items.OfType<Derived1>().Any(i => i.DerivedProperty1 == item.DerivedProperty1)
        throw new InvalidOperationException("An item with the same DerivedProperty1 already exist"); 
     items.Add(baseItem);
}

public void Add(Derived2 item)
{
    if(items.OfType<Derived2>().Any(i => i.DerivedProperty2 == item.DerivedProperty2)
        throw new InvalidOperationException("An item with the same DerivedProperty2 already exist"); 
     items.Add(baseItem);
}

暂无
暂无

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

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