有没有办法在运行时指定 PexChoose 的返回类型?例如 PexChoose.Value(name, Type)?
这对于制作根据运行时约束生成不同类型值的通用模型很有用。
有没有办法在运行时指定 PexChoose 的返回类型?例如 PexChoose.Value(name, Type)?
这对于制作根据运行时约束生成不同类型值的通用模型很有用。
您可以构建自己的帮助类,该类将通过反射调用通用版本。
例如,要创建一个非通用版本PexChoose.Value(string name)
public static class MyPexChoose
{
public static object Value(Type myType, string name)
{
// Find the PexChoose.Value() method which has a single string parameter
MethodInfo method = typeof(PexChoose).GetMethod("Value", new Type[1] {typeof(string)});
// Make and invoke the generic version of it
MethodInfo generic = method.MakeGenericMethod(myType);
return generic.Invoke(typeof(PexChoose), new object[1] { name });
}
}
然后打电话
MyPexChoose(typeof(DateTime), "MyChosen");
相当于
PexChoose<DateTime>("MyChosen");