确定运行时中的类型并将其应用于generics类型 – 我该怎么做?
我想创建一个强类型列表并在运行时决定类型。 这是我的代码。我认为它应该工作,但它没有:)
Type elementType = Type.GetType(parts[0].Trim(),false,true); var elementsBeingSet = new List();
你有什么想法如何创建一个强类型列表,其类型我将在运行时决定?
重复:这是其他版本:
使用Type.MakeGenericType(type[])
:
Type elementType = GetElementType(); // get this type at runtime Type listType = typeof(List<>); Type combinedType = listType.MakeGenericType(elementType); IList elements = (IList) Activator.CreateInstance(combinedType);
您必须使用IList
来保留结果 – 因为您不知道将在运行时使用的实际类型。
对于具有多个类型参数的generics类型,您可以使用类似Dictionary<,>
。
另请参见https://msdn.microsoft.com/en-us/library/system.type.makegenerictype.aspx
上述就是C#学习教程:确定运行时中的类型并将其应用于generics类型 – 我该怎么做?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1001641.html