如何在C#代码中知道哪个类型的变量被声明了
我希望有一些函数,如果将类Base
的变量传递给它,则返回“Base”,如果它被声明为Derived
,则返回“Derived”等。不依赖于它被分配给的值的运行时类型。
请参阅下面的代码。 关键是使用generics ,扩展方法仅用于良好的语法。
using System; static class Program { public static Type GetDeclaredType(this T obj) { return typeof(T); } // Demonstrate how GetDeclaredType works static void Main(string[] args) { ICollection iCollection = new List(); IEnumerable iEnumerable = new List (); IList iList = new List (); List 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
编辑:您也可以避免在这里使用扩展方法,因为它会导致它出现在每个 IntelliSense下拉列表中。 看另一个例子:
using System; using System.Collections; static class Program { public static Type GetDeclaredType(T obj) { return typeof(T); } static void Main(string[] args) { ICollection iCollection = new List(); IEnumerable iEnumerable = new List (); Type[] types = new Type[]{ GetDeclaredType(iCollection), GetDeclaredType(iEnumerable) }; foreach (Type t in types) Console.WriteLine(t.Name); } }
也产生了正确的结果。
如果不解析相关代码,这是不可能的。
在运行时,只有两个类型信息可用,一个值的实际类型(通过object.GetType()),如果有问题的变量是一个参数或类/实例变量,FieldInfo上的FieldType属性, 属性上的PropertyType ParameterInfo上的PropertyInfo或ParameterType。
由于传递给你的价值很可能是通过几个变量传递给你的,所以我担心这个问题甚至都没有明确定义。
啊 – 我看到你只想要方法中当前定义的类型,Expressionfunction将提供这个(Roman的答案显示了一个巧妙的方法来做到这一点)但是要注意尝试在方法之外使用它…本质上你是让编译器的generics类型推断推断出有问题的类型但这意味着所使用的变量并不总是您可以看到的变量。 它可能是编译器合成变量的变量,例如:
string x = "x"; Console.WriteLine(x.GetDeclaredType()); // string Console.WriteLine(((object)x).GetDeclaredType()); // object
由于编译器合成了一个临时变量,在该变量中将对象引用放置到x。
只需递归GetType()直到你点击对象。