简体   繁体   English

VB.NET并使用“ Dim”键入推断

[英]VB.NET and type inference using “Dim”

I'm coming from a C# background and I really like the type inference that C# 3.0 has. 我来自C#背景,我真的很喜欢C#3.0的类型推断。 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. 我正在尝试在VB.NET中做类似的事情(其中一些可能出现),但是在某些情况下,编译器在推断类型方面似乎并不那么出色。

For example, I have a method that returns an object of type System.Guid. 例如,我有一个返回System.Guid类型对象的方法。 In C# I'd do this and the variable 'prop' would be of type Guid through inference. 在C#中,我会这样做,并且变量“ prop”将通过推理成为Guid类型。

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

However, if I do a similar thing in VB.NET: 但是,如果我在VB.NET中做类似的事情:

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

I get prop as type System.Object. 我得到道具作为类型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. 我已经使用了一些VB.NET项目设置,但是它唯一改变的是稍后将其用作Guid时是否警告该对象属于Object类型。

Any ideas? 有任何想法吗? I'm thinking the use of generics should allow the compiler to tell beyond a doubt what type prop should be. 我认为使用泛型应该可以使编译器毫无疑问地告诉我们prop应该是什么类型。


@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". @J Cooper:好的,我确实启用了该设置,但是我只是重新阅读了该编译器选项的文档,并且显示为“指定是否在变量声明中允许局部类型推断”。 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. 游民。

I'm assuming by "played with the VB.NET project settings" you mean you already did this: Type Inference in VB.NET 我通过“玩过VB.NET项目设置”来假设您已经做到了: 在VB.NET中键入推断

If not, may help 如果没有,可能会有所帮助

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). 那在C#中不起作用,并且会在VB.NET中为您提供Object(例如,实例和静态变量)。

If VB is infering the type as Object, you need to turn Option Strict On at the top of your class file at least. 如果VB将类型推断为Object,则至少需要在类文件的顶部打开Option Strict。 Once you do that, you should see that class fields do not support type inferencing. 完成此操作后,您应该看到类字段不支持类型推断。 The following raises the compiler error "Option Strict On requires all variable declarations to have an As clause". 以下内容引起编译器错误“ Option Strict On要求所有变量声明都具有As子句”。

Public Shared foo = "Test"

In general, you should use Dim inside of methods and Public/Private/Friend on the class/module level fields. 通常,应该在类/模块级别字段的方法和“公共/私有/朋友”内部使用Dim。

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

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