[英]How can i have an if statement when creating an object in c#?
I want something like this when creating an object,创建对象时我想要这样的东西,
var modelObj = new TestModel
{
Id = id,
Description = obj.Description,
if (status == 1)
{
Service = obj.Url,
Username = obj.ServiceUsername,
}
else
{
Password = obj.Password,
Token = obj.Token,
FirstName = obj.FirstName
}
}
Is this possible to do with the if statement in c# ?这可能与 c# 中的 if 语句有关吗?
Is this possible to do with the if statement in c# ?
这可能与 c# 中的 if 语句有关吗?
You can do the same thing with expressions using the conditional operator.您可以使用条件运算符对表达式执行相同的操作。
var modelObj = new TestModel
{
Id = id,
Description = obj.Description,
Service = status == 1 ? obj.Url : null,
Username = status == 1 ? obj.ServiceUsername : null,
Password = status != 1 ? obj.Password : null,
Token = status != 1 ? obj.Token : null,
FirstName = status != 1 ? obj.FirstName : null,
};
You can just do this afterwards if this is an object data assignment.如果这是对象数据分配,您可以在之后执行此操作。
var modelObj = new TestModel
{
Id = id,
Description = obj.Description
}
if (status == 1)
{
modelObj.Service = obj.Url,
modelObj.Username = obj.ServiceUsername,
}
else
{
modelObj.Password = obj.Password,
modelObj.Token = obj.Token,
modelObj.FirstName = obj.FirstName
}
Otherwise best bet is to use a class constructor instead of inline initialization.否则最好的办法是使用类构造函数而不是内联初始化。
If I suggest proper way to do it then.如果我建议正确的方法,那么。
Here in the question there is no information about type of obj.在这个问题中,没有关于 obj 类型的信息。 So I am putting that as markup Obj but that needs to replace with actual type.
所以我把它作为标记 Obj 但需要用实际类型替换。
// Here you can use specific type instead of dynamic but your code miss that.
public TestModel GetTestModel(int status, int id, Obj obj)
{
if (status == 1)
{
return new TestModel()
{
Id = id,
Description = obj.Description,
Service = obj.Url,
Username = obj.ServiceUsername,
};
}
else
{
return new TestModel()
{
Id = id,
Description = obj.Description,
Password = obj.Password,
Token = obj.Token,
FirstName = obj.FirstName
};
}
}
Here's a version of dotnetstep's answer (that's I'd be happy if he used, and then I'd delete this answer).这是dotnetstep答案的一个版本(如果他使用我会很高兴,然后我会删除这个答案)。 I like it as it is really quite clean and easy to read.
我喜欢它,因为它非常干净且易于阅读。
public TestModel CreateTestModel(int status, int id, Obj obj) =>
status == 1
? new TestModel()
{
Id = id,
Description = obj.Description,
Service = obj.Url,
Username = obj.ServiceUsername,
}
: new TestModel()
{
Id = id,
Description = obj.Description,
Password = obj.Password,
Token = obj.Token,
FirstName = obj.FirstName
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.