![](/img/trans.png)
[英]How can I decrease verbosity when inheriting from C# generic types to non-generic types?
[英]How do I merge non-generic IEnumerable in C#
我试图让一个 object 从另一个 object 继承,其中IEnumerable
类型的属性将合并在一起。
两个对象都属于相同的 class。
foreach (var property in typeof(Placeholder).GetProperties())
{
var childProperty = property.GetValue(childPlaceholder);
var parentProperty = property.GetValue(parentPlaceholder);
IEnumerable childIEnumerable = childProperty as IEnumerable;
IEnumerable parentIEnumberable = parentProperty as IEnumerable;
// How do I merge childIEnumerable with parentIEnumberable into one IEnumerable
}
LINQ Cast<T>
方法允许您将非通用 Enumerable 转换为通用 Enumerable。 假设您知道Parent
和Child
类型(其中Child: Parent
):
foreach (var property in typeof(Placeholder).GetProperties())
{
var childProperty = property.GetValue(childPlaceholder);
var parentProperty = property.GetValue(parentPlaceholder);
IEnumerable childIEnumerable = childProperty as IEnumerable;
IEnumerable parentIEnumerable = parentProperty as IEnumerable;
IEnumerable<Parent> mergedEnumerable = childIEnumerable
.Cast<Child>()
.Concat(parentIEnumerable.Cast<Parent>());
}
如果不知道具体类型,也可以转为object
:
IEnumerable<object> merged = childIEnumerable
.Cast<object>()
.Concat(parentIEnumerable.Cast<object>());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.