【发布时间】:2020-03-18 00:56:28
【问题描述】:
有一个通用函数
Result<T> F<T>(int id) { .... }
void F2<T>(Result<T> r) { ... }
还有一个字符串列表(从appsettings.json读取)。
List<(string, int)> s = new List<(string, int)> {
("int", 10),
("string", 21),
("DateTime", 31),
("int", 20)
... }
如何使用字符串列表中的项目调用F?
foreach (var (t, id) in s)
{
var result = F<???>(id); // need the type from t here
F2<???>(result);
}
我为什么问这个:
原代码有一个列表
F<int>(123);
F<string>(345);
F<int>(32);
F<Othertype>(32);
... many more ...
在源代码中。并且需要不时更新/添加。我正在尝试将其移动到配置文件中,因此我不需要每次都修改代码并重新编译代码。
【问题讨论】:
-
为什么不直接使用type参数来定义要输入的参数的类型呢?
void F<T>(IEnumerable<T> items) { access items here } -
既然你不能做到这一点(不能不把它变成
Type并使用反射),请问你的最终目标是什么?F是做什么的? -
如果您可以从实际类型开始(而不是
int/string)并且想要非常受数据控制的解决方案,请查看stackoverflow.com/questions/232535/… 和stackoverflow.com/questions/2933221/…,这应该会给您Action<int>结束...可能按照所有答案的建议放入字典中。
标签: c#