값 유형이 런타임에만 알려지면 객체 []를 double []과 같은 값 유형으로 변환 할 수 있습니까? .net 기본 제공 변환을 사용하여 object []의 객체를 value 요소 유형 (double이라고 함)으로 변환 할 수없는 경우 예외가 완벽하게 허용됩니다. 런타임시 Object []를 ValueType []으로 변환하려고 시도했습니다.
var original = new object[] { 1 , 2 , 3 , 4 , 5 , 6 }
Type resultType = typeof(double[]); // or any means of getting a type at runtime
var result = ??
다음 시도
은 실패 :# error: Object must impliment IConvertible
Convert.ChangeType(original , resultType);
# error: Object cannot be stored in an array of this type.
var result = Array.CreateInstance(resultType , original.Length);
for (int i = 0 ; i < original.Length ; i++)
{
result.SetValue(Convert.ChangeType(original[ i ] , resultType.GetElementType()) , i);
}
실제로 두 배 배열을 만들고 각 객체를 이중으로 묶어서 색인으로 설정하지 않는 이유는 무엇입니까? 간단한 루프? 잘못된 객체 배열을 처리하기 위해 "if (obj is double) {...}"을 추가 할 수 있습니다. – SimpleVar
resultType이 double 일 수는 없습니다. 런타임에 결정됩니다. 모든 값 유형이 될 수 있습니다. – SFun28
일반 Cast 확장 프로그램을 사용하지 않는 이유는 무엇입니까? ValueTypes에 제약 조건을 적용하려는 경우 확장 Cast 메서드를 사용하지만 "! typeof (T) .IsValueType"인 경우 자신의 Cast 메서드를 만들 수 있습니다. 내 대답 좀 봐. – SimpleVar