该类型必须是引用类型,以便在泛型类型或方法中将其用作参数"T"

Chr*_*isS 200 c# generics

我正在深入研究仿制药,现在我需要帮助.我在下面的'Derived'类中遇到编译错误,如主题标题所示.我看到很多其他类似的帖子,但我没有看到这种关系.有人能告诉我如何解决这个问题吗?

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)
        {

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 451

我不能重复,但我怀疑在你的实际代码中有一个约束T : class- 你需要传播它以使编译器满意,例如(很难说没有repro示例):

public class Derived<SomeModel> : Base<SomeModel> where SomeModel : class, IModel
                                                                    ^^^^^
                                                                 see this bit
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,是的就是这样.一旦我添加了类约束,编译错误就消失了.以下似乎满足了引用类型的需要. (11认同)

the*_*kip 43

如果你被限制T为一个,你会得到这个错误class


Gui*_*ish 9

如果将约束放在泛型类或方法上,则使用它的每个其他泛型类或方法都需要"至少"具有这些约束.