簡體   English   中英

從基類調用時,GetType() 會返回派生最多的類型嗎?

[英]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 始終返回實際類型。

其原因在.NET框架和CLR很深,因為 JIT 和 CLR 使用.GetType方法在內存中創建一個保存對象信息的 Type 對象,所有對對象的訪問和編譯都是通過這個類型實例。

有關詳細信息,請參閱 Microsoft Press 的“CLR via C#”一書。

輸出:

 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM