我可以做以下事情吗?
public static T Merge<T>()
{
object x = Activator.CreateInstance<T>();
//Do some stuff with x
return (T)x;
}
private static Type[] GetTypesInNamespace(Assembly assembly, string nameSpace)
{
return assembly.GetTypes().Where(
t => String.Equals(t.Namespace, nameSpace, StringComparison.Ordinal) &
!t.IsInterface).ToArray();
}
public static void Main()
{
Type[] typelist = GetTypesInNamespace(
Assembly.GetExecutingAssembly(), "Myapplication.Web.DomainObjects");
Parallel.ForEach(typelist, type =>
{
var task1 = Task.Factory.StartNew(() => Merge<type>());
// is it possible to do this way? Merge<type> ??
});
}
答案 0 :(得分:0)
如果要使用编译时不知道的类型调用泛型方法,则需要使用反射:
Parallel.ForEach(typelist, type => {
var methodInfo = typeof(YourClass).GetMethod("Merge").MakeGenericMethod(type);
var task1 = Task.Factory.StartNew(() => methodInfo.Invoke(null, new object[0]));
});
答案 1 :(得分:0)
不,你不能这样做 - 当你在编译时提前知道类型时使用泛型,但是在这种情况下你不知道。
我相信你真正想做的事情有点像这样:
public static object Merge(Type type)
{
object x = Activator.CreateInstance(type);
//Do some stuff with x
return x;
}
您的foreach声明现在看起来略有不同:
Parallel.ForEach(typelist, type =>
{
var task1 = Task.Factory.StartNew(() => Merge(type));
});