7

我想要一些函数,如果将类变量Base传递给它,则返回“Base”,如果将其声明为Derived,则返回“Derived”等。不取决于分配给它的值的运行时类型。

4

3 回答 3

15

例如,请参见下面的代码。关键是使用Generics,扩展方法只是为了更好的语法。

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

编辑: 您也可以避免在此处使用扩展方法,因为它会导致它出现在每个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);
    }
}

也会产生正确的结果。

于 2009-11-23T23:24:01.307 回答
4

如果不解析相关代码,这是不可能的。

在运行时只有两条类型信息可用,值的实际类型(通过 object.GetType()),如果所讨论的变量是参数或类/实例变量,则FieldInfo 上的FieldType属性, PropertyTypeParameterInfo上的PropertyInfo 或ParameterType。

由于传递给您的值很可能是通过几个变量传递给您的,因此恐怕这个问题甚至没有得到很好的定义。

啊 - 我看到你只想要方法中当前定义的类型,表达式功能将提供这个(罗马的答案显示了一种巧妙的方法)但要小心尝试在方法之外使用它......本质上你让编译器的泛型类型推断推断有问题的类型,但这意味着使用的变量并不总是您可以看到的变量。它可能是编译器综合变量的变量,例如:

string x = "x";
Console.WriteLine(x.GetDeclaredType()); // string
Console.WriteLine(((object)x).GetDeclaredType()); // object

由于编译器合成了一个临时变量,用于放置对 x 的对象引用。

于 2009-11-23T23:23:21.713 回答
2

只需递归 GetType() 直到你碰到对象。

于 2009-11-23T23:19:54.167 回答