在您发布的代码中,您实际上并没有在任何地方实例化该类型的对象。您只是试图将一个实例转换为System.Type
没有List<int>
意义的实例。如果您更新代码以实际创建实例,则它可以工作:
int foo = 1;
Type unboundType = typeof(List<>);
Type w = unboundType.MakeGenericType(typeof(int));
if (w == typeof(List<int>))
{
Console.WriteLine("Yes its a List<int>");
object obj = Activator.CreateInstance(w);
try
{
((List<int>)obj).Add(foo);
Console.WriteLine("Success!");
}
catch(InvalidCastException)
{
Console.WriteLine("No you can't cast Type");
}
}
也许我只是错过了你问题的症结所在。当然,根据您的逻辑,您可以根据编译时不知道的某些类型进行 if/else 检查(在您的示例中,您知道您正在使用int
,但可能在运行时可能是其他类型的所需)
编辑:只是为了提供一个真正的运行时使用示例,请考虑以下内容:
public object CreateList(Type elementType, object initialValue)
{
if (!elementType.IsAssignableFrom(initialValue.GetType()))
throw new ArgumentException("Incompatible types!");
Type unboundType = typeof(List<>);
Type listType = unboundType.MakeGenericType(elementType);
object list = Activator.CreateInstance(listType);
var addMethod = listType.GetMethod("Add");
addMethod.Invoke(list, new []{initialValue});
return list;
}
这让我们可以在运行时创建一个List<T>
未知类型/对象。一些用法:
object intList = CreateList(typeof(int), 1);
object stringList = CreateList(typeof(string), "asdf");
object objectFromSomewhere = GetMyUnknownObject();
object someUnknownListType = CreateList(objectFromSomewhere.GetType(), objectFromSomewhere);
因此,您可能无法按原样处理对象;可能IEnumerable
至少可以对待他们。但这取决于您的系统需要做什么。
编辑:忘记了IList
界面:
public IList CreateList(Type elementType, object initialValue)
{
if (!elementType.IsAssignableFrom(initialValue.GetType()))
throw new ArgumentException("Incompatible types!");
Type unboundType = typeof(List<>);
Type listType = unboundType.MakeGenericType(elementType);
IList list = (IList)Activator.CreateInstance(listType);
list.Add(initialValue);
return list;
}