IEnumerable是否可以包含多个类类型?

时间:2019-04-30 18:05:44

标签: c# containers

我目前处于一种情况,我想用不同类型的viewmodels / class来填充IEnumerable

我正在Sitecore中创建一个容器元素,并且该容器内的所有项目都应该解析为相同的IEnumerable。.

每个项目都有自己的视图模型=>因此,将实际的Item解析为C#类应该不成问题=>它只是顺序,并且能够将其全部解析为一个IEnumerable似乎很棘手=>有可能吗?

关于是否可行以及如何可行的任何建议?

3 个答案:

答案 0 :(得分:1)

您始终可以使用IEnumerable<object>,然后在进行迭代时检查对象的类型,对您来说足够了吗?

答案 1 :(得分:1)

从我能解决的问题中,我认为您需要利用// this example creates 2 polylines (one red, one blue) and add event listener // to "click", and the handler loops over "polylines" (an array with the 2 // polylines created) function initMap() { var map = new google.maps.Map(document.getElementById('map'), { zoom: 10, center: { lat: -25, lng: -50 }, mapTypeId: 'terrain' }); var isOnPolyline = function (point, polyline) { if (point instanceof google.maps.Marker) { point = point.getPosition(); } return google.maps.geometry.poly.isLocationOnEdge(point, polyline, 0.0001) || google.maps.geometry.poly.containsLocation(point, polyline); }; var red = new google.maps.Polyline({ path: [{ lat: -25.006, lng: -52 }, { lat: -25.006, lng: -51 } ], map: map, name: "red", geodesic: true, strokeColor: '#FF0000', strokeOpacity: 1.0, strokeWeight: 10 }); red.addListener("click", function (e) { polylines.map(function (p) { if (isOnPolyline(e.latLng, p)) { console.log("hey, you clicked the " + p.name + " one"); } }); }); var blue = new google.maps.Polyline({ path: [{ lat: -25, lng: -53 }, { lat: -25, lng: -50 } ], name: "blue", map: map, geodesic: true, strokeColor: '#0000FF', strokeOpacity: 1.0, strokeWeight: 6 }); blue.addListener("click", function (e) { polylines.map(function (p) { if (isOnPolyline(e.latLng, p)) { console.log("hey, you clicked the " + p.name + " one"); } }); }); var polylines = [red, blue]; } 的{​​{1}}和Inheritance概念。
示例代码:

Polymorphism

答案 2 :(得分:0)

IEnumerable只能包含单一类型的实例。但是,该类型可以是接口。因此,如果所有模型都实现相同的接口,则可以将它们全部填充到同一IEnumerable中。

相关问题