开发者

Passing a type at runtime to FirstOrDefault

I have this common code:

private bool DoItStartup(IReader reader, Type provider)
{
 /// lots of common boiler plate code
 /// like:

    var abcProvider = reader.ReaderData as AbcProvider;
    var xyzProvider = abcProvider.Provisions.FirstOrDefault<XyzProvider>(); // line 2
}

The above lines of code are there for like 50 or some providers, now L开发者_如何学Goine 2 I want to basically do this:

var xyzProvider = abcProvider.Provisions.FirstOrDefault<typeOf(provider)>();

This doesn't work, possibly because xyzProvider doesn't know it's type @ compile time? Not sure. But is there a similar pattern I can use. Otherwise I'm having to duplicate this cruft code 50 times :(


Without knowing the type of abcProvider.Provisions it's a bit hard to say for sure... but normally I don't provide any type arguments to FirstOrDefault... I just let type inference work.

Have you tried just calling:

var xyzProvider = abcProvider.Provisions.FirstOrDefault();

?

(The reason it's not working is that type arguments have to be names of types or type parameters; they can't be expressions computed at execution time.)


It sounds like you need to provide a generic parameter to either the method or the class that encloses the code above. The following should work properly (not sure how provider is being passed in

public T GetStuff() {
   var xyzProvider = abcProvider.Provisions.FirstOrDefault<T>();
}


You might need to use Generics.

There are several articles on the MSDN that cover this:

Generics (C# Programming Guide)

An Introduction to C# Generics

Generic Methods (C# Programming Guide)


Generic parameters of generic types are determined at compile type (not run time). But you want your code to get type of FirstOrDefault at runtime which causes the error.
Try using this instead:
private bool DoItStartup<T>(IReader reader, Type provider) {
...
var x=list.FirstOrDefault<T>();
}

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜