如何知道在哪个类型的变量与被声明的C#代码 [英] How to know in C# code which type a variable was declared with
本文介绍了如何知道在哪个类型的变量与被声明的C#代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想有一些函数将返回基地如果类基本
的变量传递给它,派生,如果它被宣布为派生
等不依赖于运行时类型就被分配到一个值。
I want to have some function that would return "Base" if a variable of class Base
was passed to it, "Derived" if it was declared as Derived
, etc. Not depending on runtime type of a value it was assigned to.
推荐答案
例如参见下面的代码。关键是要使用泛型,使用系统只用于很好的语法扩展方法
See code below for example. The key is to use Generics, extension method was used just for nice syntax.
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);
}
}
结果:
Result:
ICollection
IEnumerable
IList`1
List`1
编辑:
你也可以尽量避免使用扩展方法在这里,因为它会导致它出现在每一个智能感知下拉列表中。看到另一个例子:
You may also avoid using extension method here, as it would cause it to appear on every IntelliSense drop-down list. See another example:
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);
}
}
也产生正确的结果。
also produces correct results.
这篇关于如何知道在哪个类型的变量与被声明的C#代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文