繁体   English   中英

里面的 if else 语句(类视图 = 新类)

[英]if else statement inside (class view = new class)

我在使用 c# 中的 if else 语句时遇到了麻烦,老实说,我是这种编程语言的初学者。 我知道 if else 语句的基本知识,但是。 在这段代码上,我不知道该怎么办。

AccountCreateView view = new AccountCreateView()
{
    UserInfo = new UserInfoData()
    {
        if (view.ChangeRefCode == "5")
        {
            TransmissonCode = "0",
            DeliveryCode = "0"
        }
        else
        {
           TransmissonCode = "1",
            DeliveryCode = "1"
        }
    },
    UserLogin = new UserLoginData(),
    UserPassword1 = null,
    UserPassword2 = null,
};

如果我在Userinfo = new Userinfo使用 if 语句,那么我的代码将变为红色。

请帮我。 我将不胜感激任何帮助。 提前致谢。

对象初始化块中不允许使用 if 语句。 您只能将表达式放在=运算符的右侧。

您可以改用三元运算符:

UserInfo = new UserInfoData()
{
    TransmissonCode = view.ChangeRefCode == "5" ? "1" : "0",
    DeliveryCode = view.ChangeRefCode == "5" ? "1" : "0",
};

形式为x ? y : z的表达式x ? y : z x ? y : z其中x是一个计算为bool dupe 的表达式, yz是计算为兼容类型的表达式,如果x计算为true则计算为y ,否则为z

您不能为view使用对象初始值设定项:

AccountCreateView view = new AccountCreateView();
view.UserInfo = new UserInfoData() { <see first code snippet> };
view.UserLogin = new UserLoginData();
view.UserPassword1 = null;
view.UserPassword2 = null;

暂无
暂无

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

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