C# 如何将字符串[]转换为T?
我有一个如下的方法↓C# 如何将字符串[]转换为T?,c#,C#,我有一个如下的方法↓ static T GetItemSample<T>() where T : new () { if (T is string[]) { string[] values = new string[] { "col1" , "col2" , "col3"}; Type elementType = typeof(string); Array array = Ar
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();
}
}
static T GetItemSample(),其中T:new()
{
if(T是字符串[])
{
字符串[]值=新字符串[]{“col1”、“col2”、“col3”};
Type elementType=typeof(字符串);
Array Array=Array.CreateInstance(elementType,values.Length);
CopyTo(数组,0);
T obj=(T)(对象)数组;
返回obj;
}
其他的
{
返回新的T();
}
}
当我调用以下方法时出错↓
string[] ret = GetItemSample<string[]>();
string[]ret=GetItemSample();
当参数为string[]时,有人能告诉我如何使用该方法吗
thks.第一个错误('T'是一个“类型参数”,但用作“变量”
)是T is string[]
不起作用。您可以使用typeof(string[])==typeof(T)
第二个错误(“string[]”必须是具有公共无参数构造函数的非抽象类型,才能将其用作泛型类型或方法“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>();
}
}
static T GetItemSample()
{
if(typeof(string[])==typeof(T))
{
字符串[]值=新字符串[]{“col1”、“col2”、“col3”};
Type elementType=typeof(字符串);
Array Array=Array.CreateInstance(elementType,values.Length);
CopyTo(数组,0);
T obj=(T)(对象)数组;
返回obj;
}
其他的
{
返回Activator.CreateInstance();
}
}
此代码的缺点是,如果
T
没有默认构造函数而不是在编译时,它会在运行时抛出错误
static T GetItemSample<T>(T[] obj)
static T GetItemSample(T[]obj)
或
static T GetItemSample(T obj)
static T GetItemSample<T>(T obj)