C# 使用通用IEnumerable<;T>;
我已经编写了一个函数,它将接受一个通用IEnumerable并将这些对象(如果可能)映射到我想要用于算法的对象。我对泛型对象或IEnumberables没有太多经验,所以我想征求一些建议 我编写了以下代码:C# 使用通用IEnumerable<;T>;,c#,generics,C#,Generics,我已经编写了一个函数,它将接受一个通用IEnumerable并将这些对象(如果可能)映射到我想要用于算法的对象。我对泛型对象或IEnumberables没有太多经验,所以我想征求一些建议 我编写了以下代码: public static IEnumerable<OtherObject> MyObjectToOtherObject<T>(IEnumerable<T> objects) { if (objects.GetType() == t
public static IEnumerable<OtherObject> MyObjectToOtherObject<T>(IEnumerable<T> objects)
{
if (objects.GetType() == typeof(MyObject))
{
var data = (IEnumerable<MyObject>)objects;
return data.Select(x => new OtherObject() { // Map the attributes });
}
else
return null;
}
公共静态IEnumerable MyObjectTotherObject(IEnumerable对象)
{
if(objects.GetType()==typeof(MyObject))
{
变量数据=(IEnumerable)对象;
返回数据。选择(x=>newotherobject(){//映射属性});
}
其他的
返回null;
}
这在我的代码中不起作用,因为即使输入列表的类型是MyObject
,它也会返回null。我就是不知道如何将我的IEnumerable
转换为IEnumerable
。我做错什么了吗
提前谢谢
我为所有的困惑感到抱歉。我问错了。亚历克斯帮了我很多,谢谢你看起来您不需要通用方法,如果您总是知道源和目标类型,您可以这样做:
public static IEnumerable<DestObject> ObjectToObject1(IEnumerable<SourceObject> objects)
{
return data.Select(x => new DestObject() { // Map the attributes });
}
公共静态IEnumerable对象对象1(IEnumerable对象)
{
返回数据。选择(x=>newdestObject(){//映射属性});
}
这是错误的
objects.GetType() == typeof(MyObject)
正确:
objects.GetType() == typeof(IEnumerable<T>)
如果您正在检查该类型是否可以转换为其他类型:
objects.GetType().GetGenericArguments()[0].IsAssignableFrom(typeof(MyObject))
或者就像
typeof(T).IsAssignableFrom(typeof(MyObject))
我认为您要做的是构建一个通用映射方法,它可以将任何give
T
映射到您的具体类Object1
。您需要提供一个进行映射的映射函数
假设你有一个(过于做作的)例子:
然后从一个IEnumerable
开始,您的方法将需要获取列表,并使用Func
进行映射
var input = new List<SourceObject>(){
new SourceObject{AString="Str1"},
new SourceObject{AString="Str2"}
};
var result = MyObjectToOtherObject(input, x => new DestObject{TheProperty = x.AString});
var输入=新列表(){
新的SourceObject{AString=“Str1”},
新的SourceObject{AString=“Str2”}
};
var result=myobjecttotherobject(输入,x=>newdestObject{TheProperty=x.AString});
这是这样完成的:
public static IEnumerable<DestObject> MyObjectToOtherObject<T>(IEnumerable<T> objects, Func<T,DestObject> mapping)
{
return data.Select(mapping);
}
公共静态IEnumerable MyObjectTotherObject(IEnumerable对象,函数映射)
{
返回数据。选择(映射);
}
正如您所看到的,分离方法在这一点上或多或少是无用的。这正是
Select
所做的。对象
永远不会属于MyObject
类型,因此
(objects.GetType() == typeof(MyObject))
将始终返回false
,因为object
是某个通用集合(IEnumerable
)
你可以尝试使用
typeof(T) == typeof(MyObject)
使用objects.OfType()。通过
Object
选择(x=>newObject1()…)是指所有对象的内置根,还是您自己的类?如果是后者,请选择一个更好的名称IEnumerable
是协变的,所以除了IEnumerable result=objects之外,您还尝试做什么代码>?对不起!为了简单起见,我更改了名称,我会尽快更改!你;我们仍然混淆了Object1
和OtherObject
。正确,稍后我将添加更多类型。它甚至还没有通过if语句,尽管我在代码中发现了一个错误。我给了函数一个列表。我该怎么做才能让它检查列表中对象的类型而不是IEnumerable的类型?谢谢你的编辑!请原谅我问了这么一个令人困惑的问题!
(objects.GetType() == typeof(MyObject))
typeof(T) == typeof(MyObject)