![](/img/trans.png)
[英]“this” keyword type when called on an object of derived class from base class
[英]Will GetType() return the most derived type when called from the base class?
從基類調用時,GetType() 會返回派生最多的類型嗎?
例子:
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
}
或者我應該只創建一個派生類必須實現的抽象方法,如下所示?
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)
,即使所討論的變量被聲明為對A
的引用。
您的GetSubType()
方法沒有理由。
GetType
總是返回實際實例化的類型。 即最衍生的類型。 這意味着您的GetSubType
的行為就像GetType
本身一樣,因此是不必要的。
要靜態獲取某種類型的類型信息,您可以使用typeof(MyClass)
。
您的代碼有一個錯誤: System.Attribute.GetCustomAttributes
返回Attribute[]
而不是Type
。
輸出:
GetType: Parent: 'Playground.ParentClass' Child: 'Playground.ChildClass' Child as Parent: 'Playground.ChildClass' GetParentType: Parent: 'Playground.ParentClass' Child: 'Playground.ParentClass' Child as Parent: 'Playground.ParentClass'
程序.cs:
using Playground;
var parent = new ParentClass();
var child = new ChildClass();
var childAsParent = child as ParentClass;
Console.WriteLine("GetType:\n" +
$"\tParent: '{parent.GetType()}'\n" +
$"\tChild: '{child.GetType()}'\n" +
$"\tChild as Parent: '{childAsParent.GetType()}'\n");
Console.WriteLine("GetParentType:\n" +
$"\tParent: '{parent.GetParentType()}'\n" +
$"\tChild: '{child.GetParentType()}'\n" +
$"\tChild as Parent: '{childAsParent.GetParentType()}'\n");
子類.cs
namespace Playground
{
public class ChildClass : ParentClass
{
}
}
父類.cs
namespace Playground
{
public class ParentClass
{
public Type GetParentType()
{
return typeof(ParentClass);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.