Will GetType() return the most derived type when called from the base class?(从基类调用时,GetType() 会返回派生最多的类型吗?)
问题描述
GetType() 从基类调用时会返回派生最多的类型吗?
Will GetType() return the most derived type when called from the base class?
例子:
public abstract class A
{
private Type GetInfo()
{
return System.Attribute.GetCustomAttributes(this.GetType());
}
}
public class B : A
{
//Fields here have some custom attributes added to them
}
或者我应该只创建一个派生类必须实现的抽象方法,如下所示?
Or should I just make an abstract method that the derived classes will have to implement like the following?
public abstract class A
{
protected abstract Type GetSubType();
private Type GetInfo()
{
return System.Attribute.GetCustomAttributes(GetSubType());
}
}
public class B : A
{
//Fields here have some custom attributes added to them
protected Type GetSubType()
{
return GetType();
}
}
推荐答案
GetType() 将返回实际的实例化类型.在您的情况下,如果您在 B 的实例上调用 GetType(),它将返回 typeof(B),即使在question 被声明为对 A 的引用.
GetType() will return the actual, instantiated type. In your case, if you call GetType() on an instance of B, it will return typeof(B), even if the variable in question is declared as a reference to an A.
您的 GetSubType() 方法没有理由.
There is no reason for your GetSubType() method.
这篇关于从基类调用时,GetType() 会返回派生最多的类型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从基类调用时,GetType() 会返回派生最多的类型吗?
基础教程推荐
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
