代码之家  ›  专栏  ›  技术社区  ›  John Gietzen

C/.NET:typeof(variable)是一种可能的语言功能吗?

  •  9
  • John Gietzen  · 技术社区  · 14 年前

    在一些不同的情况下,我试图用coax方法将声明的类型从变量中去掉,这与声明相对较远,但结果发现 typeof(T) 仅适用于类型名。

    我想知道是否会有什么突破性的改变允许 typeof(variable) 也。

    例如,使用此代码:

    class Animal { /* ... */ }
    class Goat : Animal { /* ... */ }
    
    /* ... */
    
    var g = new Goat();
    Animal a = g;
    
    Console.WriteLine(typeof(Goat));
    Console.WriteLine(typeof(Animal));
    Console.WriteLine(g.GetType());
    Console.WriteLine(a.GetType());
    

    你会得到如下信息:

    山羊
    动物
    山羊
    山羊

    为什么不可能这样做:

    Console.WriteLine(typeof(g));
    Console.WriteLine(typeof(a));
    

    山羊
    动物

    我粗略地看了一下规范,没有发现任何冲突。我想这会澄清“为什么是这种类型?”当使用 typeof 操作员。

    我知道编译器是有能力的。使用扩展方法的实现实际上很简单:

    public static Type TypeOf<T>(this T variable)
    {
        return typeof(T);
    }
    

    但这感觉很肮脏,滥用了编译器的类型推断。

    5 回复  |  直到 9 年前
        1
  •  3
  •   jason    14 年前

    class Animal { }
    
    string Animal;
    Type t = typeof(Animal); // uh-oh!
    
        2
  •  4
  •   Gabriel Magana    14 年前

    "0".GetType()
    

        3
  •  0
  •   Daniel DeSousa    14 年前

    Type t1 = myObject.GetType();
    

        4
  •  0
  •   tnyfst    14 年前

    public class Animal {}
    string Animal;
    Type t = typeof(Animal);