The type must be a reference type in order to use it as parameter 'T' in the generic type or method

10/17 08:07
阅读数 13

问题:

I'm getting deeper into generics and now have a situation I need help with. 我正在深入研究泛型,现在遇到需要帮助的情况。 I get a compile error on the 'Derived' class below as shown in the subject title. 如主题标题所示,我在下面的“派生”类上遇到编译错误。 I see many other posts similar to this one but I'm not seeing the relationship. 我看到许多其他与此类似的帖子,但是我没有看到这种关系。 Can someone tell me how to resolve this? 有人可以告诉我如何解决吗?

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

        }
    }
}

解决方案:

参考一: https://en.stackoom.com/question/R4EK
参考二: https://stackoom.com/question/R4EK
展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部