VB.NET 和使用“Dim"的类型推断 [英] VB.NET and type inference using "Dim"

查看:26
本文介绍了VB.NET 和使用“Dim"的类型推断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我来自 C# 背景,我非常喜欢 C# 3.0 的类型推断.我试图在 VB.NET 中做类似的事情(其中一些似乎是可能的),但在某些情况下,编译器似乎不太擅长推断类型.

I'm coming from a C# background and I really like the type inference that C# 3.0 has. I'm trying to do similar things in VB.NET (some of which appear possible), but in some cases the compiler seems to be not nearly as good at inferring the type.

例如,我有一个返回 System.Guid 类型对象的方法.在 C# 中,我会这样做,并且变量prop"将通过推理成为 Guid 类型.

For example, I have a method that returns an object of type System.Guid. In C# I'd do this and the variable 'prop' would be of type Guid through inference.

var prop = RegisterProperty<Guid>(...);

但是,如果我在 VB.NET 中做类似的事情:

However, if I do a similar thing in VB.NET:

Dim prop = RegisterProperty(Of Guid(...)

我得到 prop 作为 System.Object 类型.我已经使用了一些 VB.NET 项目设置,但它唯一改变的是,当我稍后将它用作 Guid 时,我是否收到该对象类型为 Object 的警告.

I get prop as type System.Object. I've played with some of the VB.NET project settings but the only thing it changes is whether I get a warning that the object is of type Object when I use it later as a Guid.

有什么想法吗?我认为泛型的使用应该允许编译器毫无疑问地告诉 prop 应该是什么类型.

Any ideas? I'm thinking the use of generics should allow the compiler to tell beyond a doubt what type prop should be.

@J Cooper:好的,我确实打开了该设置,但我只是重新阅读了该编译器选项的文档,它显示指定是否允许在变量声明中进行局部类型推断".我相信它对我不起作用的原因是我在我的班级中声明了静态字段.我猜即使它们在声明时被初始化,编译器此时也不支持类型推断.无赖.

@J Cooper: ok, I did have that setting turned on, but I just re-read the documentation for that compiler option and it reads "Specifies whether to allow local type inference in variable declarations". I believe the reason it's not working for me is that I'm declaring static fields in my class. I guess even though they are initialized when declared, the compiler doesn't support type inference at that point. Bummer.

推荐答案

您在下面提到您正在尝试在静态变量声明中执行此操作.这在 C# 中不起作用,并且会在 VB.NET 中为您提供对象(例如和静态).

You mention below that you're trying to do this in a static variable declaration. That won't work in C#, and will give you Object in VB.NET (for instance and statics).

这篇关于VB.NET 和使用“Dim"的类型推断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆