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

发布于 2024-09-07 03:49:52 字数 666 浏览 4 评论 0原文

(不太确定我是否正确地表达了问题...)

我想创建一个 lambda 表达式,它将接受一个对象,尝试将其转换为传入的类型,并打印到控制台,无论它是否成功。

乍一看,lambda 表达式似乎是完成此任务的一种相当愚蠢的方法,但我真的很想知道我做错了什么,这样我就可以更好地发展我的技能。

VS 给了我一个关于下面表达式中的第二个“T”的设计者错误,告诉我它没有定义)

这是我离开的地方:

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

(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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

沉鱼一梦 2024-09-14 03:49:52

我不能具体代表 VB,但我不知道 .NET 委托中有任何此类概念。虽然委托类型可以是通用的,但我不认为您可以在类型参数中将特定的委托实例保留为“打开”,以由调用者提供。不过,这是一个有趣的想法。

当然,您可以轻松编写一个通用方法来执行此操作,这可能是正确的方法。这是一个有趣的情况,您可以使用单一方法接口来表达所需的功能,但不能将其表达为委托类型。唔。只是为了讨论,界面可能是这样的:

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

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);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文