从基础对象列表获取派生对象的属性

时间:2017-09-15 07:16:58

标签: c# generics collections abstract

我正在寻找从我的派生类中获取属性的简单方法,它继承了抽象类。

我的代码:

public abstract class PointLayer
{
    public abstract Type Type { get;}
}
public class PointLayer<T> : PointLayer
{
    #region PROPERTIES
    public override Type Type { get; }
    public string MapName { get; private set; }
    public MapType MapType { get; private set; }
    public Point<T> Point { get; private set; }
    #endregion

    #region C'TOR
    /// <summary>
    /// Constructor creating PointLayer
    /// </summary>
    /// <param name="mapName">Map name</param>
    /// <param name="mapType">Map type</param>
    /// <param name="point">Point</param>
    public PointLayer(string mapName, MapType mapType, Point<T> point)
    {
        MapName = mapName;
        Point = point;
        MapType = mapType;
    }
    #endregion
}

我尝试从图层列表的元素中获取MapName。

Layers = new List<PointLayer>();

1 个答案:

答案 0 :(得分:0)

Layers = new List<PointLayer>();

图层是父类的列表。您无法从父类访问子属性,因为您无法保证PointLayer类型的对象具有属性MapName。

如果您确定对象实际上是PointLayer类型,您可以强制转换它们:

    var GenericLayers = new List<PointLayer<int>>();
    List<PointLayer> Layers = GenericLayers.Select(x => (PointLayer)x).ToList();

    List<int> MapNames = Layers.Select(x => ((PointLayer<int>)x).MapName).ToList();

编辑:

鉴于您的答案需要不同类型的PointLayer列表,您应该只使用PointLayer列表:

public abstract class PointLayer
{
    public abstract Type Type { get;}
    public abstract string MapName { get; protected set; }
    public abstract MapType MapType { get; protected set; }
    public abstract Point Point { get; protected set; }
}
public class PointLayer<T> : PointLayer
{
    #region PROPERTIES
    public override Type Type { get; }
    public override string MapName { get; protected set; }
    public override MapType MapType { get; protected set; }
    public override Point Point { get; protected set; }
    #endregion

    #region C'TOR
    /// <summary>
    /// Constructor creating PointLayer
    /// </summary>
    /// <param name="mapName">Map name</param>
    /// <param name="mapType">Map type</param>
    /// <param name="point">Point</param>
    public PointLayer(string mapName, MapType mapType, Point<T> point)
    {
        Type=typeof(T);
        MapName = mapName;
        Point = point;
        MapType = mapType;
    }
    #endregion
}

然后

Layers = new List<PointLayer>();
var MapNames=Layers.Select(x=>x.MapName);

Point<T>继承point,我认为这是您可以做的最好的事情。根据{{​​1}}超过Point<T>的功能,这可能就足够了。虽然您无法分辨点的类型参数是什么,因为您只能在运行时知道这一点,因此无法解决这个问题。如果Point是抽象的,并且Point中包含的所有方法都会产生很小的差异。