如何将字符串[]转换为T ?

本文关键字:转换 字符串 | 更新日期: 2023-09-27 18:05:26

我有一个像下面这样的方法↓

    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[]>();

是否有人可以告诉我如何使用该方法当参数是string[] ?

呢。

如何将字符串[]转换为T ?

第一个错误('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没有默认构造函数,它会在运行时抛出错误,而不是在编译时抛出错误。

你的方法必须像

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

static T GetItemSample<T>(T obj)