我想要一些函数,如果类 Base
的变量被传递给它,它将返回“Base”,如果它被声明为 Derived
,则返回“Derived”,等等。不依赖于分配给它的值的运行时类型。
最佳答案
例如,请参见下面的代码。关键是使用泛型,扩展方法只是为了漂亮的语法。
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);
}
}
结果:
ICollection
IEnumerable
IList`1
List`1
编辑: 您也可以避免在此处使用扩展方法,因为它会导致它出现在 every 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);
}
}
也产生正确的结果。
关于c# - 如何在 C# 代码中知道变量声明的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1786750/