gpt4 book ai didi

c# - c# System.Type 类型如何具有名称属性

转载 作者:太空狗 更新时间:2023-10-29 21:09:22 24 4
gpt4 key购买 nike

我很确定这与实现接口(interface)和继承有关。

在 C# 中,System.Type 类如何具有属性名称?当我从元数据或使用对象浏览器示例 Type 类的代码时,我看到 Type 类没有:

string Name

定义在任何地方。

我还看到 Type 继承自 MemberInfo 并实现了 _Type 和 IReflect(像这样):

public abstract class Type : MemberInfo, _Type, IReflect

基类 MemberInfo 具有以下属性:

public abstract string Name { get; }

据我所知,由于 abstract 修饰符,这个必须在派生类中被覆盖。我没有在类型中看到它...

然后在_Type接口(interface)中有一个属性:

string Name { get; }

因为它在一个接口(interface)中,所以它也没有自己的实现。

Name 是在哪里定义的?它如何在 System.Type 类中具有值?还是我不明白继承和实现接口(interface)是如何为这个类工作的

最佳答案

请注意 System.Type 本身就是一个抽象类。这意味着它可以在子类中被覆盖。事实上,如果您执行以下操作,您可以看到运行时的类型实际上并不是 System.Type 的:

typeof(Type).GetType().FullName; // System.RuntimeType

System.RuntimeType 是您不会在文档中看到的内部类型,但它确实覆盖了 Name 属性。它看起来有点像这样:

namespace System
{
internal class RuntimeType : Type, ISerializable, ICloneable
{
...
public override string Name
{
get { ... }
}
}
}

请参阅 official documentation 中的这条注释:

Type is an abstract base class that allows multiple implementations. The system will always provide the derived class RuntimeType. In reflection, all classes beginning with the word Runtime are created only once per object in the system and support comparison operations.

关于c# - c# System.Type 类型如何具有名称属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18153937/

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