如何比较 System.Type?

4
DataSet.Tables[0].Columns[0] 中,我们有一个 DataType 属性。现在,我想遍历 Columns 并根据 DataType 中的 Type 执行一些操作。如何做到这一点?
foreach(var c in DataSet.Tables[0].Columns)
{
  if (c.DataType == System.String) {} //error 'string' is a 'type', which is not valid in the given context

}
3个回答

14

使用typeof运算符:

if (c.DataType == typeof(string))
{
    // ...
}

5
@Marc表示:那不是同一件事情。c.DataType是一个Type,而不是一个字符串。你的代码将始终为假。 - LukeH
我想知道我漏掉了什么,谢谢!我发表了这个评论希望它能被驳斥或确认。 - Marc

4

试试这个...

if (c.DataType == typeof(string)) {}

4
if (c.DataType == typeof(string))
{
    // code
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接