ゴール
object [] Source、object Target、およびFieldInfo Varがあります(Var.FieldType.IsArrayはtrueです)。Var.SetValue(Target、Source)を実行したい。ただし、「object[]」->「anotherType[]」は変換できません。
サンプル実行
object[]Source=new object[2]{"Hello","World"};
Var.SetValue(Target,Source); //Cannot Convert "object[]"->"string[]"
[注:int、double、floatなどを使用できるようにしたい。そうでなければ、この問題は簡単になります]
リサーチ
Varを使用: var配列を作成できないため、使用できません
ジェネリックを使用する:
これは
myField.SetValue(target,GenericCastArray<string>(source));
ただし、
Type someType=typeof(string); //or int, or float
(myfield.SetValue(target,GenericCastArray< someType > (source))
* http://social.msdn.microsoft.com/Forums/en-US/csharplanguage/thread/fe14d396-bc35-4f98-851d-ce3c8663cd79/ * null参照例外を返します、私はthis.GetType()だと思います
編集:Meh Solution コメントに基づいて、object[]からstring[]に変換することは不可能です。ただし、次のコードは適切に機能します。
object[]Source=null;
Type basetype=Var.FieldType.GetElementType();
int l=somelength;
if (basetype.IsEquivalentTo(typeof(string))) Source = new string[l];
//repeat for all types
source=//run your Reflection here
var.SetValue(target,source);