如何在C#代码中知道哪个类型变量被声明了

Mis*_*sha 7 c# types declaration

我希望有一些函数,如果将类的变量Base传递给它,则返回"Base",如果声明为Derived,则"Derived" ,等等.不依赖于它被分配给的值的运行时类型.

Rom*_*iko 15

请参阅下面的代码.关键是使用泛型,扩展方法仅用于良好的语法.

using System;

static class Program
{
    public static Type GetDeclaredType<T>(this T obj)
    {
        return typeof(T);
    }

    // Demonstrate how GetDeclaredType works
    static void Main(string[] args)
    {
        ICollection iCollection = new List<string>();
        IEnumerable iEnumerable = new List<string>();
        IList<string> iList = new List<string>();
        List<string> list = null;

        Type[] types = new Type[]{
            iCollection.GetDeclaredType(),
            iEnumerable.GetDeclaredType(),
            iList.GetDeclaredType(),
            list.GetDeclaredType()
        };

        foreach (Type t in types)
            Console.WriteLine(t.Name);
    }
}
Run Code Online (Sandbox Code Playgroud)

结果:

ICollection
IEnumerable
IList`1
List`1
Run Code Online (Sandbox Code Playgroud)

编辑: 您也可以避免在这里使用扩展方法,因为它会导致它出现在每个 IntelliSense下拉列表中.看另一个例子:

using System;
using System.Collections;

static class Program
{
    public static Type GetDeclaredType<T>(T obj)
    {
        return typeof(T);
    }

    static void Main(string[] args)
    {
        ICollection iCollection = new List<string>();
        IEnumerable iEnumerable = new List<string>();

        Type[] types = new Type[]{
                GetDeclaredType(iCollection),
                GetDeclaredType(iEnumerable)
        };

        foreach (Type t in types)
            Console.WriteLine(t.Name);
    }
}
Run Code Online (Sandbox Code Playgroud)

也产生了正确的结果.