gpt4 book ai didi

c# - 该类型必须是引用类型才能将其用作泛型类型或方法中的参数 'T'

转载 作者:IT王子 更新时间:2023-10-29 03:29:45 32 4
gpt4 key购买 nike

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

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

关于c# - 该类型必须是引用类型才能将其用作泛型类型或方法中的参数 'T',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6451120/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com