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() 会返回派生最多的类型吗?
基础教程推荐
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- c# Math.Sqrt 实现 2022-01-01
- 将 XML 转换为通用列表 2022-01-01