简体   繁体   English

我可以在lamba表达式中包含泛型类型参数吗? (VB.NET 2010)

[英]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. 我想创建一个接受对象的lambda表达式,尝试将其转换为传入的Type,并打印到控制台,无论是否成功。

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. 乍一看,lambda表达式似乎是完成此任务的一种很愚蠢的方法,但是我真的很想知道我做错了什么,以便我更好地发展自己的技能。

VS gives me a designer error about the second "T" in the expression below, telling me it isn't defined) VS给我一个有关以下表达式中第二个“ T”的设计器错误,告诉我未定义)

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. 我不能专门为VB说话,但是总体上我不知道在.NET委托中有任何这样的概念。 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);
}

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

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