gpt4 book ai didi

c# - 在c#中使用字符串数据类型列表创建元组

转载 作者:行者123 更新时间:2023-12-03 17:25:48 25 4
gpt4 key购买 nike

我需要从字符串中的数据类型列表创建元组,但没有得到任何解决方案。

这是我想要做的示例。

string[] dataType = {"int", "float", "datetime"};

//I want to create list like this but dynamically datatype come from db.
//List<Tuple<int, string, string>> list = new List<Tuple<int, string, string>>();

List<Tuple<dataType[0],dataType[1], dataType[2]>> list = new List<Tuple<dataType[0],dataType[1], dataType[2]>>();
//Here datatype value is in string so I want to convert string to actual datatype.

或者,如果对此有任何替代解决方案,请指导我。

最佳答案

这是为了扩展我对问题的评论,并向您展示我在那里的意思。

创建一个 Tuple 的列表并不难动态地从字符串格式的类型列表中获取。例如,使用反射:

private Type InferType(string typeName)
{
switch (typeName.ToLowerInvariant())
{
case "int":
return typeof(int);
case "float":
return typeof(float);
default:
return Type.GetType($"System.{typeName}", true, true);
}
}

private object CreateListOfTupleFromTypes(string[] types)
{
var elementTypes = types.Select(InferType).ToArray();

// Get Tuple<,,>
var tupleDef = typeof(Tuple)
.GetMethods(BindingFlags.Static | BindingFlags.Public)
.First(mi => mi.Name == "Create"
&& mi.GetParameters().Count() == elementTypes.Length)
.ReturnType
.GetGenericTypeDefinition();

// Get Tuple<int, float, DateTime>
var tupleType = tupleDef.MakeGenericType(elementTypes);

// Get List<Tuple<int, float, DateTime>>
var listType = typeof(List<>).MakeGenericType(tupleType);

// Create list of tuple.
var list = Activator.CreateInstance(listType);

return list;
}

问题是因为列表是使用仅在运行时已知的类型创建的,在您的代码中,您永远不能将该列表用作强类型列表。即 List<Tuple<int, float, DateTime>> .

当然,通过使用 ITuple 在您的代码中使用列表时,您可以使生活更轻松。 :
var list = new List<ITuple>();
list.Add(new Tuple<int, float, DateTime>(...);

int value1 = (int)list[0][0];
float value1 = (float)list[0][1];
DateTime value1 = (DateTime)list[0][2];

但是,如果你这样做,那么使用 Tuple 就没有意义了。 .您只需要 List<object[]> .

所以,这又回到了我的问题,你的代码中的元组列表是什么?

关于c# - 在c#中使用字符串数据类型列表创建元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61118042/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com