gpt4 book ai didi

c# - 接口(interface)如何调用对象类的ToString方法

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

根据我的理解,interface 不是像其他类一样从 Object 派生的,因此如何允许接口(interface)调用 ToString() 方法一个 Object 类。

interface I1
{
}

class D
{
I1 i;
public D()
{
string s = i.ToString(); // why compiler doesn't complain here?
}
}

编辑

正如评论中指出的,Everything derived from Object,这里是一些自相矛盾的文章

https://blogs.msdn.microsoft.com/ericlippert/2009/08/06/not-everything-derives-from-object/

最佳答案

您可以使用 Object 中的方法,因为 Standard ECMA-334 C# Language Specification是这样说的:

14. Expressions

14.3 Member lookup

14.3.1 Base types

For purposes of member lookup, a type T is considered to have the following base types:

[...]

  • If T is an interface-type, the base types of T are the base interfaces of T and the class type object.

这就是为什么您可以在使用接口(interface)作为类型的变量上调用 ToString(),即使该接口(interface)中没有定义 ToString() 方法。

关于c# - 接口(interface)如何调用对象类的ToString方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55673510/

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