C# typeof 与 示例的GetType()

创建两个类

namespace ConsoleApp1;

public interface IBagItem
{
    public uint UId { get; set; }
}

public class BagItem : IBagItem
{
    public uint UId { get; set; }
}

public class DreamIslandBagItem : IBagItem
{
    public uint UId { get; set; }
}

测试 

namespace ConsoleApp1;

public class TypeOfTest
{
    public static void Test()
    {
        var typeOfTest = new TypeOfTest();
        {
            IBagItem bagItem  = new BagItem();
            typeOfTest.TypeOf(bagItem);
        }

        Console.WriteLine("-------------------------");
        {
            IBagItem bagItem  = new DreamIslandBagItem();
            typeOfTest.TypeOf(bagItem);
        }

        Console.WriteLine("-------------------------");
        {
            BagItem bagItem  = new BagItem();
            typeOfTest.TypeOf(new List(){bagItem});
        }

        Console.WriteLine("-------------------------");
        {
            DreamIslandBagItem bagItem  = new DreamIslandBagItem();
            typeOfTest.TypeOf(new List(){bagItem});
        }
        
        /***
            ConsoleApp1.IBagItem
            IBagItem                      
            ConsoleApp1.BagItem           
            BagItem                       
            -------------------------     
            ConsoleApp1.IBagItem          
            IBagItem                      
            ConsoleApp1.DreamIslandBagItem
            DreamIslandBagItem            
            -------------------------     
            ConsoleApp1.BagItem           
            BagItem                       
            ConsoleApp1.BagItem           
            BagItem                       
            -------------------------     
            ConsoleApp1.DreamIslandBagItem
            DreamIslandBagItem            
            ConsoleApp1.DreamIslandBagItem
            DreamIslandBagItem 
         */
    }

    public void TypeOf(T t) where T : IBagItem
    {
        Console.WriteLine(typeof(T).FullName);
        Console.WriteLine(typeof(T).Name);
        Console.WriteLine(t.GetType().FullName);
        Console.WriteLine(t.GetType().Name);
    }
    
    public void TypeOf(List list) where T : IBagItem
    {
        Console.WriteLine(typeof(T).FullName);
        Console.WriteLine(typeof(T).Name);
        Console.WriteLine(list[0].GetType().FullName);
        Console.WriteLine(list[0].GetType().Name);
    }
}

如果 入参是 单个 T则:

typeof 输出 指向示例的类型 也就是 IBagItem

GetType() 输出 源类型

如果入参是List则:

typeof 、GetType()  都 输出 源类型

参考

Type-testing operators and cast expressions test the runtime type of an object - C# | Microsoft Learn

Expressions - C# language specification | Microsoft Learn 

你可能感兴趣的:(工作,细节,c#,开发语言)