是否可以根据需要的类型获取methodInfo:
var wantedType = typeof(propertyReference);
var methodInfo = typeof(List<wantedType>).GetMethod("Contains",
new[] { typeof(wantedType) });
......还有这个:
var list ="(some, list, here)".Split(new[] { ',' },
StringSplitOptions.RemoveEmptyEntries).Select(wantedType.Parse).ToList()
如果是,那么这样做的正确方法是什么?
答案 0 :(得分:1)
由于wantedType
是运行时类型,因此您需要先获取该类型的泛型定义。使用MakeGenericType
来实现此目的:
var t = typeof(List<>).MakeGenericType(wantedType);
现在你可以通过反射调用它的任何方法,就好像它是普通类型的那样:
t.GetMethod("Contains").Invoke(myList, new[] { instanceOfWantedType });
其中MyValue
是wantedType
类型的实例。
你的第二个例子类似,只需通过反射调用Parse
- 方法:
var m = wantedType.GetMethod("Parse", new[] { typeof(string) });
var list = stringArray.Select(x => m.Invoke(null, new[] { x })).ToList()
但请注意,列表非常不明确,因为所有元素都是object
类型。