如何执行typeof [英] How to execute a typeof
本文介绍了如何执行typeof的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含一些列的数据表.我想获取一列的类型并将其放在此命令中:
Hi,
I have a DataTable that contains some columns. I want to get the type of one column and put it in this command:
dataRow1.Field<"I wrote here dataRow1.Table.Columns["columnName"].DataType>("columnName")
但这没用.
在此先谢谢您.
But it''s not worked.
Thanks in advance.
推荐答案
您应该在通用参数中定义实际的数据类型.例如,如果列为string
,则:
You should define the actual datatype in the generic parameter. For example if the column isstring
, then:
dataRow1.Field<string>("columnName")
等等.
不幸的是,泛型不能那样工作.
泛型类型参数必须在编译时已知,并且不能是运行时因变量
我建议要么使用通用基类(对象),要么创建一种方法来测试运行时数据类型,并使用正确的设计时指定的通用类型参数:
Unfortunately generics don''t work like that.
Generic type parameters must be known at compile-time and cannot be a runtime dependent variable
I would suggest either working with a common base class (object) or creating a method that tests the runtime datatype and uses the correct, design-time specified, generic type argument:
if(dataRow1.Table.Columns["columnName"].DataType == typeof(string))
{
//use dataRow1.Field<string>("columnName")
}
else if (dataRow1.Table.Columns["columnName"].DataType == typeof(int))
{
//use dataRow1.Field<int>("columnName")
}
...
这篇关于如何执行typeof的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文