简体   繁体   English

如何设置局部通用变量

[英]How to set local generic variable

I want to set local variable BarService<T1> service; 我想设置局部变量BarService<T1> service; as described on class Foo . Foo类所述。

Code is as follows: 代码如下:

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();
    }
}

Can anyone clear the error for me? 谁能为我清除错误?

If you want to use an open generic type as the type of your field, then you have to make the whole class generic, not just the method: 如果要使用开放的通用类型作为字段的类型,则必须使整个类通用,而不仅仅是方法:

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>();
    }
}

It is unclear what the relationship between GetAll<T2>() and the rest of the code is, but with luck the above would work. 尚不清楚GetAll<T2>()与其余代码之间的关系是什么,但幸运的是,上述方法可以正常工作。

Of course, whether you can actually make your class Foo into a generic class depends on how it's used elsewhere in the code. 当然,实际上是否可以将类Foo变成通用类,取决于代码中其他地方如何使用它。 There's not enough context in your question to know if there are going to be other problems. 您的问题中没有足够的上下文来知道是否还会有其他问题。 But the above is the basic idea. 但是以上是基本思想。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM