gpt4 book ai didi

c# - 带有 IFormattable 参数的函数不接受字符串

转载 作者:太空宇宙 更新时间:2023-11-03 17:52:38 24 4
gpt4 key购买 nike

我有一个处理字符串输入的函数。

    public string Foo(string text)
{
// do stuff with text and
// return processed string
}

我在很多地方都调用了这个,我将 guid 转换为这样的字符串:
string returnValue = Foo(bar.ToString());

我真正想要的是接受任何可以转换为字符串的对象类型作为输入。所以我尝试修改函数如下:
    public string Foo(IFormattable text)
{
var textAsString = text.ToString();
// do stuff with textAsString
// and return processed string
}

这意味着我所有的调用都更简单:
string returnValue = Foo(bar);

它适用于所有具有 .ToString 方法的对象类型;除了字符串:)

如果我尝试将字符串传递给函数,则会收到以下编译错误:
Argument type 'string' is not assignable to parameter type 'System.IFormattable'  

这看起来很奇怪,因为 String 有一个 ToString() 方法。

为什么这不起作用?

最佳答案

简单地说, System.String 未实现 IFormattable .

如果文档对您来说还不够:

object x = "a string";
Console.WriteLine(x is IFormattable); // False

鉴于 ToString() is declared on object ,为什么不只是有:
public string Foo(object text)
{
var textAsString = text.ToString();
// do stuff with textAsString
// and return processed string
}

确实, ToString() method declared by IFormattable 无论如何都不是您要调用的那个-您没有传递格式字符串或格式提供程序。

此外:

Which seems really odd because String HAS a ToString() method.



接口(interface)不是鸭式的。仅仅因为一个类型具有接口(interface)所需的所有成员并不意味着它实现了该接口(interface)。

关于c# - 带有 IFormattable 参数的函数不接受字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19939777/

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