如何设置局部通用变量

本文关键字:局部 变量 设置 何设置 | 更新日期: 2023-09-27 18:01:39

我想按照Foo类的描述设置局部变量BarService<T1> service;

代码如下:

class Foo
{
    // error i got here and want to use this instead of using dynamic
    BarService<T> service;
    //dynamic service
    internal void SetBarService<T>() where T : class, new()
    {
       service = new BarService<T>();
    }
    internal IEnumerable<T2> GetAll<T2>() where T2 :class
    {
        return service.GetAll<T2>();
    }
}
public class BarService<T> where T : class
{
    internal IEnumerable<T> GetAll<T>()
    {
        throw new NotImplementedException();
    }
}

谁能帮我清除这个错误?

如何设置局部通用变量

如果您想使用一个开放泛型类型作为字段的类型,那么您必须使整个类泛型,而不仅仅是方法:

class Foo<T> where T : class, new()
{
    BarService<T> service;
    internal void SetBarService()
    {
       service = new BarService<T>();
    }
    internal IEnumerable<T2> GetAll<T2>() where T2 :class
    {
        return service.GetAll<T2>();
    }
}

目前还不清楚GetAll<T2>()和其他代码之间的关系是什么,但幸运的是,上面的代码可以工作。

当然,是否真的可以将类Foo变成泛型类取决于它在代码中的其他地方是如何使用的。你的问题没有足够的背景来判断是否还会有其他问题。以上是基本思路