rec*_*ive 15 c# arrays reflection casting
如果我在编译时知道类型或者它是一个通用参数,这将是非常直接的,因为我可以做类似的事情myArray.Cast<T>()但实际上我实际拥有的是这个.我没有已知的类型或通用参数.我有一个System.Type变量.
// could actually be anything else
Type myType = typeof(string);
// i already know all the elements are the correct types
object[] myArray = new object[] { "foo", "bar" };
Run Code Online (Sandbox Code Playgroud)
我可以做一些反射魔法来获得string[]包含相同数据的引用吗?(string在编译时不知道的地方)
Sve*_*ven 27
这不是真正的演员阵容(我正在分配一个新阵列并复制原件),但也许这可以帮到你?
Type myType = typeof(string);
object[] myArray = new object[] { "foo", "bar" };
Array destinationArray = Array.CreateInstance(myType, myArray.Length);
Array.Copy(myArray, destinationArray, myArray.Length);
Run Code Online (Sandbox Code Playgroud)
在这段代码中,destinationArray将是string[](或任何类型的数组myType)的实例.