C# typeof 与 示例的GetType()

发布时间:2024年01月11日

创建两个类

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>(){bagItem});
        }

        Console.WriteLine("-------------------------");
        {
            DreamIslandBagItem bagItem  = new DreamIslandBagItem();
            typeOfTest.TypeOf(new List<DreamIslandBagItem>(){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 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<T>(List<T> 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<T>则:

typeof 、GetType()? 都 输出 源类型

文章来源:https://blog.csdn.net/qq_36790074/article/details/135537754
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。