无法从“字符串"转换为"System.IFormatProvider" [英] cannot convert from 'string' to 'System.IFormatProvider'

查看:54
本文介绍了无法从“字符串"转换为"System.IFormatProvider"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这段代码给我这个错误:

This code gives me this error:

var n = "9/7/2014 8:22:35 AM";
var m = n.ToString("yyyy-MM-dd'T'HH:mm:ssZ");

但是此代码可以正常工作,并以正确的格式返回日期.

But this code works as it should and returns the date in the proper format.

var n = DateTime.Now;
var m = n.ToString("yyyy-MM-dd'T'HH:mm:ssZ");

任何人都知道为什么第一个代码不起作用以及如何使其起作用?

Anyone know why the first code isn't working and how to get it working?

推荐答案

您需要了解静态输入的工作原理.在第一个中, n 的类型为 string .类型 string 确实具有 ToString()方法,但是该方法不带任何参数并返回相同的字符串对象,或者带格式提供程序.由于您提供了一个参数,因此编译器假定您的意思是第二个版本,但是类型不匹配.

You need to understand how static typing works. In the first one, the type of n is string. The type string does have a ToString() method, but that method either takes no arguments and returns the same string object, or it takes a format provider. Since you provided an argument, the compiler assumes you meant the second version, but the types don't match.

也许您想做的是先将字符串转换为日期,这可以通过使用 DateTime Parse TryParse进行解析来完成方法:

Perhaps what you are trying to do is convert a string into a date first, which can be done by parsing it using DateTime's Parse or TryParse methods:

var n = DateTime.Parse("9/7/2014 8:22:35 AM");

在这里,我们将 string 转换为 DateTime . n 的类型为 DateTime .

Here, we convert a string to DateTime. The type of n is DateTime.

我认为在弄清楚C#时使用 var 可能不是一个好主意.如果您明确列出类型,则将对正在发生的事情有更深入的了解,并且编译器会更早地标记错误.在这种情况下,您将在第一行得到错误,这很明显.它将抱怨将字符串分配给 DateTime .没有关于 IFormatProvider 的怪异东西,这一点都不明显.您的代码如下所示:

I think it might be a good idea not to use var while you're figuring out C#. If you explicitly list the types, you'll gain a greater understanding of what's going on, and the compiler will flag errors earlier. In this case, you'll get the error on the very first line, and it'll be obvious. It will complain about assigning a string to a DateTime. No weird stuff about IFormatProvider, which is not at all obvious. Your code would look like this:

DateTime n = "9/7/2014 8:22:35 AM";
string m = n.ToString("yyyy-MM-dd'T'HH:mm:ssZ");

在此示例中,第一行会出现错误,然后您可以清楚地看到您正在尝试分配的字面值(字符串"9/7/2014 8:22:35 AM")将 string 键入为 DateTime 类型的变量,该变量将不起作用.

In this example, you'll get an error on line one, and then you can clearly see that you are trying to assign a literal value (the string "9/7/2014 8:22:35 AM") of type string to a variable of type DateTime, which can't work.

这篇关于无法从“字符串"转换为"System.IFormatProvider"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆