C# 初始化器条件赋值
在 ac# 初始化程序中,如果条件为 false,我不想设置属性。
像这样:
ServerConnection serverConnection = new ServerConnection()
{
ServerInstance = server,
LoginSecure = windowsAuthentication,
if (!windowsAuthentication)
{
Login = user,
Password = password
}
};
可以做到吗? 如何?
In a c# initialiser, I want to not set a property if a condition is false.
Something like this:
ServerConnection serverConnection = new ServerConnection()
{
ServerInstance = server,
LoginSecure = windowsAuthentication,
if (!windowsAuthentication)
{
Login = user,
Password = password
}
};
It can be done?
How?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这在初始化器中是不可能的;您需要创建一个单独的
if
语句。或者,您可以编写
(取决于您的 ServerConnection 类的工作方式)
This is not possible in an initializer; you need to make a separate
if
statement.Alternatively, you may be able to write
(Depending on how your
ServerConnection
class works)你不能这样做; C# 初始值设定项是名称 = 值对的列表。有关详细信息,请参阅此处: http://msdn.microsoft .com/en-us/library/ms364047(VS.80).aspx#cs3spec_topic5
您需要将
if
块移动到以下行。You can't do this; C# initializers are a list of name = value pairs. See here for details: http://msdn.microsoft.com/en-us/library/ms364047(VS.80).aspx#cs3spec_topic5
You'll need to move the
if
block to the following line.我怀疑这会起作用,但是以这种方式使用逻辑有点违背了使用初始化程序的目的。
I suspect this would work, but using logic this way sort of defeats the purpose of using the initializer.
正如其他人提到的,这不能在初始化程序中完成。仅将 null 分配给属性而不是根本不设置它是否可以接受?如果是这样,您可以使用其他人指出的方法。这是一个替代方案,它可以完成您想要的操作,并且仍然使用初始化语法:
在我看来,它实际上并不重要。除非您正在处理匿名类型,否则初始化语法只是一个很好的功能,可以使您的代码在某些情况下看起来更整洁。我想说,如果它牺牲了可读性,就不要特意使用它来初始化所有属性。改为执行以下代码没有任何问题:
As others mentioned, this can't exactly be done within an initializer. Is it acceptable to just assign null to the property instead of not setting it at all? If so, you can use the approach that others have pointed out. Here's an alternative that accomplishes what you want and still uses the initializer syntax:
In my opinion, it shouldn't really matter much. Unless you're dealing with anonymous types, the initializer syntax is just a nice to have feature that can make your code look more tidy in some cases. I would say, don't go out of your way to use it to initialize all of your properties if it sacrifices readability. There's nothing wrong with doing the following code instead:
注意:我不推荐这种方法,但如果它必须在初始化程序中完成(即您使用LINQ或其他必须是单个语句的地方),您可以使用此方法:
Note: I do not recommend this approach, but if it must be done in an initializer (i.e. you're using LINQ or some other place where it has to be a single statement), you can use this:
这个怎么样:
How about this: