2011-08-14 5 views
-3

나는 방법이 내가 ↓어떻게 문자열 [] T로 변환 할 수 있습니까?

같은 방법을 호출 할 때 ↓

static T GetItemSample<T>() where T : new() 
    { 
     if (T is string[]) 
     { 
      string[] values = new string[] { "col1" , "col2" , "col3"}; 
      Type elementType = typeof(string); 
      Array array = Array.CreateInstance(elementType, values.Length); 
      values.CopyTo(array, 0); 
      T obj = (T)(object)array; 
      return obj; 
     } 
     else 
     { 
      return new T(); 
     } 
  } 

오류가 아래처럼

string[] ret = GetItemSample<string[]>(); 

는 사람이 어떻게 PARAM 문자열은 [때이 방법을 사용하는 나에게 말했다 수 있나요 ]?

thks.

답변

4

첫 번째 오류 ('T' is a 'type parameter' but is used like a 'variable')는 T is string[]이 작동하지 않을 것입니다. typeof(string[])==typeof(T)

두 번째 오류 ('string[]' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'UserQuery.GetItemSample<T>()')는 기본 생성자가없는 string[]에는 일반 제약 조건이 없으므로 하나만 있어야합니다.

static T GetItemSample<T>() 
    { 
     if (typeof(string[])==typeof(T)) 
     { 
      string[] values = new string[] { "col1" , "col2" , "col3"}; 
      Type elementType = typeof(string); 
      Array array = Array.CreateInstance(elementType, values.Length); 
      values.CopyTo(array, 0); 
      T obj = (T)(object)array; 
      return obj; 
     } 
     else 
     { 
      return Activator.CreateInstance<T>(); 
     } 
  } 

이 코드의 단점은 T 더 기본 생성자 대신 컴파일시가없는 경우는 런타임 에러가 발생한다는 것입니다.

1

당신의 방법은

static T GetItemSample<T>(T[] obj) 

또는

static T GetItemSample<T>(T obj) 
처럼해야합니다
관련 문제