开发者

Extract Generic Type From Enclosing Generic

I want s开发者_JS百科omething like this:

class Foo<T>{...}

class Boo<T>{

   Queue<T> stuff = new Queue<T>();

   public void Boo(Foo<T>){...};
}

...

//Extract the generic type - string - to define the type
//of MyBoo.
var MyBoo = new Boo(new Foo<string>());

I get the error "generic type 'Boo' requires '1' type arguments. Ya, I fixed the problem by stating the template type explicitly, but I'd like to know if there was/is a way to extract that type implicitly, rather than having to state it explicitly.

This other post may be related, but I'm not sure.


You can't do it implicitly directly with the constructor of a generic type, but you could from a generic method, e.g. in a non-generic class:

public static class Boo
{
    public Boo<T> Create<T>(Foo<T> foo)
    {
        return new Boo<T>(foo);
    }
}

Then:

// myBoo will be inferred to be of type Boo<string>
var myBoo = Boo.Create(new Foo<string>());

Of course, it doesn't have to be another class called Boo - it could be something completely different, and it could be an instance method of something else:

var factory = new BooFactory();
var myBoo = factory.Create(new Foo<string>());

The important point is that it's a generic method - type arguments can be inferred for generic methods, but not for generic types.


Type inference works only with methods. So if you have generic method and it is clear how to substitute generic parameter it will be substituted by compiler. For new operator it doesn't work so consider creating factory method like Create that will produce instances of Boo. Otherwise impossible.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜