对于仿制药默认值 [英] Default value for generics

查看:171
本文介绍了对于仿制药默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何创建默认为在VB中的通用?在C#中我可以打电话:

  T变量=默认(T);
 

  1. 如何做到这一点在VB?
  2. 如果这只是返回null(C#)或没有(VB)发生在值类型又是什么?
  3. 有没有一种方法来指定一个自定义类型的默认值是什么?举例来说,如果我想的默认值是相当于调用参数的构造函数上我的课。
解决方案

问题1:

 昏暗的变量为t
' 要么 '
昏暗的变量为T =无
' 要么 '
昏暗的变量作为新T()
 

请注意,后者只有在你指定的结构约束的一般类型(引用类型,新T()在VB做别的东西比默认(T)在C#中)。

问题2:

有关价值类型结构的所有成员都调零出来的,即所有引用类型成员都设置为没有),所有值类型依次调零了。​​

和没有,因为字符串是引用类型,它的没有的结果的字符串作为建议在对方的回答。

问题3:

没有,有没有办法来指定。有关于这个堆栈溢出一些线程已经,如<一href="http://stackoverflow.com/questions/333829/why-cant-i-define-a-default-constructor-for-a-struct-in-net">here.乔恩已经发布的<一href="http://stackoverflow.com/questions/333829/why-cant-i-define-a-default-constructor-for-a-struct-in-net#333840">excellent 的解释这是为什么。

How do I create the default for a generic in VB? in C# I can call:

T variable = default(T);

  1. How do I do this in VB?
  2. If this just returns null (C#) or nothing (vb) then what happens to value types?
  3. Is there a way to specify for a custom type what the default value is? For instance what if I want the default value to be the equivalent to calling a parameterless constructor on my class.

解决方案

Question 1:

Dim variable As T
' or '
Dim variable As T = Nothing
' or '
Dim variable As New T()

Notice that the latter only works if you specify the Structure constraint for the generic type (for reference types, New T() in VB does something else than default(T) in C#).

Question 2:

For value types all members of the struct are "nulled" out, i.e. all reference type members are set to null (Nothing) and all value types are in turn nulled out.

And no, since string is a reference type, it does not result in "" for strings as suggested in the other answer.

Question 3:

No, there's no way to specify this. There are some threads about this on Stack Overflow already, e.g. here. Jon has posted an excellent explanation why this is.

这篇关于对于仿制药默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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