该类型必须是引用类型,才能在通用类型或方法中将其用作参数“ T”

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

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)

{

}

}

}

回答:

我无法复制,但我 怀疑 您的实际代码中存在某个约束条件,例如T : class,您需要传播该约束以使编译器满意(如果没有一个复制实例,很难确定):

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

^^^^^

see this bit

以上是 该类型必须是引用类型,才能在通用类型或方法中将其用作参数“ T” 的全部内容, 来源链接: utcz.com/qa/430193.html

回到顶部