[英]How do I initialize a private static readonly HashSet<char>?
I want a private, constant member我想要一个私人的、固定的成员
private static readonly HashSet<char> _nameChars
in my controller, containing the characters ' ', 'a', 'A', ..., 'z', 'Z'
.在我的控制器中,包含字符' ', 'a', 'A', ..., 'z', 'Z'
。 The purpose is for server-side validation of a form.目的是用于表单的服务器端验证。 But how do I initialize that HashSet
?但是我如何初始化那个HashSet
?
private static readonly HashSet<char> _nameChars = ?????
Is there a good way of doing that?有什么好的方法吗? I know that C++ has bracket initialization for std::set
.我知道 C++ 有std::set
括号初始化。
C# also has collection initializers: C#还具有集合初始化器:
private static readonly HashSet<char> _nameChars = new HashSet<char> { 'a', 'b', ...};
You might also use a constructor that takes IEnumerable<T>
argument: 您可能还会使用带有IEnumerable<T>
参数的构造函数:
private static readonly HashSet<char> _nameChars = new HashSet<char>("abcde...");
I find the 2nd approach more readable. 我发现第二种方法更具可读性。
Alternative way:替代方式:
static IReadOnlyCollection<char> ExcludedFields = new HashSet<char> {
'a', 'b', ...
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.