【问题标题】:Generic Classes in c# [duplicate]c#中的泛型类[重复]
【发布时间】:2019-03-20 05:28:28
【问题描述】:

我有以下模板类和接口

public class UseCaseResponse<T> where T : class 
{
  //......
}

public interface IPresenter<T> where T : UseCaseResponse<T>, new()
{
    void Handle(T response);
}
public class JsonPresenter<T> : IPresenter<T> where T : UseCaseResponse<T>, new()
{

    public void Handle(T response)
    {
        throw new NotImplementedException();
    }
}

现在我的问题是如何创建不同 JSonPresenter 的对象 就像我能做到的一样,

ServiceCollection s = new ServiceCollection();
s.AddScoped<UseCaseResponse<Person>, UseCaseResponse<Person>>();
var provider = s.BuildServiceProvider();
var p = (UseCaseResponse<Person>)p.GetService(typeof(UseCaseResponse<Person>));

这可行,但我如何获得JsonPresenter&lt;UseCaseResponse&lt;Person&gt;&gt; 对象?

【问题讨论】:

标签: c# generics


【解决方案1】:

对于泛型,您只需要在创建类型的实例时指定具体的类型参数。对于您想要的JsonPresenter&lt;UseCaseResponse&lt;Person&gt;&gt;,它将是:

var presenter = new JsonPresenter<UseCaseResponse<Person>>();

现在你可以这样做了:

//p is the UseCaseResponse instance from your second code sample
presenter.Handle(p); 

【讨论】:

  • 它不起作用。 "无隐式引用转换"
  • OP 使用“奇怪的递归模板模式”——因此类需要从该类的泛型派生,例如 Person:UseCaseResponse&lt;Person&gt;(以便 UseCaseResponse&lt;Person&gt; 工作)。我认为没有办法让JsonPresenter&lt;UseCaseResponse&lt;Person&gt;&gt; 编译(至少没有任何合理的理智)
  • 哦,我完全错过了,对不起
  • 经过进一步检查 - 奇怪的递归模式在这里适用于哪里?我认为任何类都不需要类型参数来从自身派生,还是我误解了什么?
  • 哦,我现在明白了:-D 是时候再次审查泛型了:-D
猜你喜欢
  • 2019-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-27
  • 2021-07-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多