开发者

Can I include a Generic type parameter in a lamba expression? (VB.NET 2010)

(Not really sure if I phrased the question correctly...)

I want to create a lambda expression that would take an Object, attempt to convert it to a passed-in Type, and print to the console whether it was successful or not.

At a 开发者_如何转开发glance, the lambda expression may seem a pretty silly way to accomplish this task, but I'd really like to know what I'm doing wrong, so I can better grow my skill set.

VS gives me a designer error about the second "T" in the expression below, telling me it isn't defined)

This is where I left off:

Sub MyMethod(ByVal param as Object)
    Dim quickMethod = Sub (Of T)(o as Object) 
                          Console.WriteLine(TryCast(o, T) IsNot Nothing)                                
                      End Sub

    quickMethod(Of myClass1)(param)
    quickMethod(Of myClass2)(param)
    quickMethod(Of myClass3)(param) 
    quickMethod(Of myClass4)(param)

    'further logic below... ;)    
End Sub


I can't speak for VB specifically, but I'm not aware of any such concept in .NET delegates in general. While a delegate type can be generic, I don't believe you can leave a particular delegate instance "open" in a type parameter, to be provided by the caller. It's an interesting idea though.

Of course, you could easily write a generic method to do this, and that's probably the right way to go. It's an interesting situation where you could have a single-method interface expressing the desired functionality, but you can't express that as a delegate type. Hmm. Just for the sake of discussion, the interface could be something like this:

interface IConverter
{
    bool IsConvertible<T>(object input);
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜