【问题标题】:The type must be a reference type in order to use it as parameter 'T' in the generic type or method类型必须是引用类型才能在泛型类型或方法中用作参数“T”
【发布时间】:2011-06-23 08:13:35
【问题描述】:

我正在深入研究泛型,现在遇到需要帮助的情况。我在下面的“派生”类上收到编译错误,如主题标题所示。我看到许多其他类似的帖子,但我没有看到这种关系。谁能告诉我如何解决这个问题?

using System;
using System.Collections.Generic;


namespace Example
{
    public class ViewContext
    {
        ViewContext() { }
    }

    public interface IModel
    {
    }

    public interface IView<T> where T : IModel 
    {
        ViewContext ViewContext { get; set; }
    }

    public class SomeModel : IModel
    {
        public SomeModel() { }
        public int ID { get; set; }
    }

    public class Base<T> where T : IModel
    {

        public Base(IView<T> view)
        {
        }
    }

    public class Derived<SomeModel> : Base<SomeModel> where SomeModel : IModel
    {

        public Derived(IView<SomeModel> view)
            : base(view)
        {
            SomeModel m = (SomeModel)Activator.CreateInstance(typeof(SomeModel));
            Service<SomeModel> s = new Service<SomeModel>();
            s.Work(m);
        }
    }

    public class Service<SomeModel> where SomeModel : IModel
    {
        public Service()
        {
        }

        public void Work(SomeModel m)
        {

        }
    }
}

【问题讨论】:

  • 我没有收到任何编译错误
  • 此代码未显示该错误。编译干净。

标签: c# generics


【解决方案1】:

我无法重现,但我怀疑在您的实际代码中存在T : class 的某个约束 - 您需要传播它以使编译器满意,例如(很难肯定地说,没有复制示例):

public class Derived<SomeModel> : Base<SomeModel> where SomeModel : class, IModel
                                                                    ^^^^^
                                                                 see this bit

【讨论】:

  • 谢谢,是的,就是这样。一旦我添加了类约束,编译错误就消失了。以下似乎满足了引用类型的需要。
  • 这是有效的。 public class Base where T : class, IModel { public Base(IView view) { } } public class Derived : Base where SomeModel : class, IModel { public Derived(IView view) : base(view) { SomeModel m = (SomeModel)Activator.CreateInstance(typeof(SomeModel));服务 s = 新服务(); s.Work(m); } }
  • 也提供了帮助:) 谢谢 :) 作为旁注,如果 IMO 已经在界面中应用了相同的约束,我认为我们不应该一次又一次地复制它。
【解决方案2】:

如果您将T 限制为class,则会收到此错误

【讨论】:

    【解决方案3】:

    如果您对泛型类或方法施加约束,则使用它的所有其他泛型类或方法都需要“至少”具有这些约束。

    【讨论】:

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