0

Currently I have an object of type IList<object> and I need to convert to another type of IList using Type object.

eg.

Type t = typeof(MyType);
var list = OtherClass.MyFunction(myParam param);

The var list is of type IList<object> and I need it to be of type IList<t>

Currently I have a static function and call for reflection, but this is called within a loop and need to minimize the maximum time spent in my loops.

Anyone know any other way to perform this conversion without using reflection?

With delegate maybe?


Domains and Ranges of sets in algebra

State whether the following functions are well-defined. If they are, then give the Domain, Co-domain and Range and state whether the functions are one-to-one and/or onto and give your reasoning. If they are not well defined, then explain why not.

a) f: J → J, f(x) = 3x + 1

b) g: N → N, g(x) = x2 – 1

c) h: N → R, h(x) = +x

d) j: {words} → {letters}, j(x) = initial letter of x

I will appreciate if someone gives correct answers to each part. Thanks

4

2 回答 2

5

您可以使用Enumerable.Cast<T>()

var myList = list.Cast<MyType>().ToList();
于 2013-04-25T00:07:56.703 回答
0

如果 T 在编译时未知,我想你可以:

var type = typeof(int);
IList<object> myList = (new object[]{1, 2, 3, 4, 5}).ToList();
var mi = typeof(Enumerable).GetMethod("Cast");
var mRef = mi.MakeGenericMethod(type);
object myIEnumerableOfInt = mRef.Invoke(null, new object[]{myList});
mi = typeof(Enumerable).GetMethod("ToList");
mRef = mi.MakeGenericMethod(type);
IList myIListOfInt = (IList)mRef.Invoke(null, new object[]{myIEnumerableOfInt});

...但是在这里使用这种反射意味着您将永远无法引用它,因为IList<int>您可以在代码中推断出的最多的myIListOfIntIList... IMO 这里的强制转换完全没用。

于 2013-04-25T00:34:28.053 回答