简体   繁体   English

C#中的泛型是否与Python 3的Optional等效?

[英]Is there the equivalent of Python 3's Optional for generics in C#?

I want to have a List of a type Regex. 我想要一个正则表达式类型的列表。 But the list can have None (or null). 但是列表中可以没有(或为空)。

So I'd like the syntax List<Regex|Null> or something similar. 所以我想要语法List<Regex|Null>或类似的东西。

  • There is a blog post here that has the same concept. 有一个博客张贴在这里有相同的概念。

But I'm hoping there may be something baked into C# I am overlooking. 但是我希望我忽略了C#中的某些东西。

  • Python 3 has Optional . Python 3具有Optional Does C# have anything like that? C#有这样的东西吗?

  • I did see something about using a question mark here . 我确实在这里看到了有关使用问号的信息 But it didn't give an example that made sense to me. 但这没有给出一个对我有意义的例子。


new T?(x)

I have seen: 我见过:

  • a post entitled "Discriminated Unions" here that sort of hits the point of what I am after. 一个名为“识别联合”后在这里那种打的什么我找的点。
  • Also this entitled "Multiple generic Types in one List" one . 另外这个题为“一个列表中选择多个泛型类型” 一个

I also think there are often Union classes for this kind of thing, having seen similar SO posts 我也认为这类事情经常会出现联盟类,见过类似的帖子


What would be the simplest C# code to define such a Typed generic List, and add either null or a Regex to it? 定义这种类型化泛型列表并向其添加nullRegex的最简单的C#代码是什么?

Actually you do not have to do anything to get nulls in such list: 实际上,您无需执行任何操作即可在此类列表中获取空值:

var list = new List<Regex>();
list.Add(null);

This is because Regex is a class and this is how it works. 这是因为正则表达式是一个类,这就是它的工作方式。

var regex = CreateMyRegex();
list.Add(regex);

Regardless of what the method CreateMyRegex returns, null or instance, it will get added to list. 无论CreateMyRegex方法返回什么,null或instance,它都会被添加到列表中。

Actually currently you cannot make it the other way around - forbid nulls in such list. 实际上,当前您无法进行其他操作-禁止在此类列表中使用null。 There is a possibility that this will be possible in C# 8. 有可能在C#8中实现。

If you would like to do this with structs you can do it as well: 如果您想对结构执行此操作,也可以执行以下操作:

var list = new List<int?>();
list.Add(null);

The question mark syntax is not restricted to generics in c#, you can make nullable structures as any other variable type: 问号语法不限于c#中的泛型,您可以将可空结构设为任何其他变量类型:

int? number = null;

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

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