【问题标题】:why is this generic not resolved at compile time?为什么这个泛型在编译时没有解决?
【发布时间】:2011-05-25 16:37:51
【问题描述】:

我有以下代码。我希望它打印出来:

A
B
C
DONE

而是打印

P
P
P
DONE

为什么?

更新
我不是在寻求解决方案。我想知道为什么会这样。我认为泛型是在编译时解决的。据我所知,它应该能够在编译时将这些解析为正确的方法,但显然不是,我不明白为什么。我正在寻找原因的解释,而不是解决方案。

代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication50
{
    class Parent
    {
        public string FieldName { get; set; }
        public string Id { get; set; }
    }

    class ChildA : Parent
    {
        public string FieldValue { get; set; }
    }

    class ChildB : Parent
    {
        public DateTime? Start { get; set; }
        public DateTime? End { get; set; }
    }

    class ChildC : Parent
    {
        public ICollection<string> Values { get; set; }
    }
    class Program
    {
        void Validate<T>(Parent item) where T : Parent
        {
            if (item is T)
                Validate(item as T);
        }
        void Validate(ChildA filter)
        {
            Console.WriteLine("A");
        }

        void Validate(ChildB filter)
        {
            Console.WriteLine("B");
        }

        void Validate(ChildC filter)
        {
            Console.WriteLine("C");
        }

        void Validate(Parent filter)
        {
            Console.WriteLine("P");
            // do nothing placeholder so the code will compile
        }

        ArgumentException Fail(Parent filter, string message)
        {
            return new ArgumentException(message, filter.FieldName);
        }

        void Run()
        {
            var list = new List<Parent> {
                new ChildA(), new ChildB(), new ChildC() };
            Validate<ChildA>(list[0]);
            Validate<ChildB>(list[1]);
            Validate<ChildC>(list[2]);
        }
        public static void Main()
        {
            new Program().Run();
            Console.WriteLine();
            Console.WriteLine("DONE");
            Console.ReadLine();
        }
    }
}

【问题讨论】:

标签: c# generics


【解决方案1】:

泛型是一个运行时概念。这是它们与 C++ 模板的主要区别,后者是一个编译时概念。

在方法Validate&lt;T&gt; 中,T 在编译时总是未知,即使调用者明确指定。 唯一 Validate&lt;T&gt; 知道T 是它来自Parent

更具体地说,泛型不能用于生成代码。您正在尝试的将在 C++ 下工作,因为当 C++ 看到对 Validate&lt;ClassA&gt; 的调用时,它实际上会重新编译 Validate&lt;T&gt;,因此模板成为一种代码生成。在C#下,Validate&lt;T&gt;只编译一次,所以泛型不能作为一种代码生成。

在 C++ 下,对 Validate&lt;ClassA&gt; 的调用将在编译时实例化模板。

在 C# 下,对 Validate&lt;ClassA&gt; 的调用将在运行时实例化泛型方法。

【讨论】:

  • 值得注意的是,即使没有反射,在 .NET 中也有可能有一个方法,当传入由字母 X 和 Y 组成的字符串(例如“XYXXYXY”)时,它会调用类型为X&lt;Y&lt;X&lt;X&lt;Y&lt;X&lt;Y&lt;fnord&gt;&gt;&gt;&gt;&gt;&gt;&gt; 的泛型方法,有效地证明了单个.NET 程序可能使用的不同类的数量基本上是无限的——这种情况与C++ 非常不同,C++ 中每种不同的类型都需要有与之关联的代码。
  • >>泛型是一个运行时概念。不!这个答案是不正确的。对不起,这是完全不正确的。 C# 中的泛型是编译时间。编译器根据使用情况为它们生成具体的代码和指令。甚至存在编译器生成额外代码的问题,甚至有一个解决方案(优化预编译库的数量)。 ref - J.Richter 第 4 版,泛型,第 314 页。否则它将永远不会与原始非泛型代码一样快,但等于反射。
【解决方案2】:

重载解析是在编译时执行的,而不是在运行时。

通常的解决方案是在这里使用简单的虚拟调度:

class Parent
{
    public virtual  void Validate() { Console.WriteLine("P"); }
}

class ChildA : Parent
{
    public override void Validate() { Console.WriteLine("A"); }
}

class ChildB : Parent
{
    public override void Validate() { Console.WriteLine("B"); }
}

void Run()
{
    var list = new List<Parent> { new ChildA(), new ChildB() };
    list[0].Validate(); // prints "A"
    list[1].Validate(); // prints "B"
}

【讨论】:

  • 这按预期工作,但与访客无关。这是简单的虚拟调度。
【解决方案3】:

该项目将始终被验证为父类型。

泛型背后的想法是你没有特定于类型的代码。因此它的“泛型”部分。

您仅限于类的一个分支,在这种情况下是 Parent 以及从它派生的所有东西。这意味着代码应该像传入的对象是 Parent 类型一样执行。

正如 dtb 所说,访问者模式可以应用在这里。

另一个想法是简单地有一个接口,它定义了每个类必须支持的 Validate() 方法。我认为这将是一条更好的路线。

【讨论】:

    【解决方案4】:

    假设您可以使用 C# 4.0,您可以通过使用“动态”关键字来消除 C# 编译器将执行的静态重载解析。只需将您的验证功能更改为:

        void Validate<T>(Parent item) where T : Parent
        {
            dynamic dyn = item;
            if (item is T)
                Validate(dyn);
        }
    

    输出将是:

    C:\tmp>temp.exe
    A
    B
    C
    
    DONE
    

    我刚刚从@juharr 的 Eric Lippert 博客链接中了解到这一点。阅读有关dynamic type on msdn 的更多信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多