开发者

How can I convert string[] to T?

开发者 https://www.devze.com 2023-03-28 04:39 出处:网络
I have a method like below ↓ static T GetItemSample<T>() where T : new () { if (T i开发者_运维知识库s string[])

I have a method like below ↓

    static T GetItemSample<T>() where T : new ()
    {
        if (T i开发者_运维知识库s 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();
        }
  }

There is an error when I invoke the method like ↓

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

Is anybody could told me how to use the method when the param is string[] ?

thks .


The first error ('T' is a 'type parameter' but is used like a 'variable') is that T is string[] won't work. You could use typeof(string[])==typeof(T)

The second error ('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>()') is that string[] has no default constructor but the generic constraint requires it to have one.

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>();
        }
  }

The disadvantage of this code is that it throws an error at runtime if T has no default constructor instead of at compile-time.


Your method must be like

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

or

static T GetItemSample<T>(T obj)  
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号