简体   繁体   English

使用c#对象初始化对类成员进行条件初始化

[英]conditional initialization of class member using c# object initialization

I am having a simple class with 3 not null integer members 我有一个简单的类,具有3个不为null的整数成员

public class Test
{
    public int Test1 { get; set; }
    public int Test2 { get; set; }
    public int Test3 { get; set; }
}

Now I want to use something like this 现在我想使用这样的东西

        int? var1 = null;
        int var2 = 2;
        int var3 =5;
       var t =  new Test
        {
            Test1 = var1, // (error) Initialize Test1 only when var1 is not null
            Test2 = var2,
            Test3 = var3
        };

ie I just want to initialize member Test1 only if var1 is not null, so somehow I need to put a check while initialization. 即我只想仅在var1不为null的情况下初始化成员Test1,所以以某种方式我需要在初始化时进行检查。 I know its a simple question and can be done in diifferent ways but as I am refactoring the existing code and generalizing it, I need solution through Object Initialization only. 我知道这是一个简单的问题,可以通过不同的方式完成,但是当我重构现有代码并对其进行概括时,我仅需要通过对象初始化解决方案。 Looking simple to me but somehow could not able to find solution by myself 对我来说看起来很简单,但是我自己却无法找到解决方案

Not much experienced programmer, so really appreciate any help 没有太多经验的程序员,所以非常感谢任何帮助

That wouldn't compile anyway, I don't think. 我认为那还是无法编译。 But either way the value will get the default value of an int if you don't initialize it. 但是,无论哪种方式,如果不初始化,该值都将获取int的默认值。 An equivalent would be: 等效项为:

    int? var1 = null;
    int var2 = 2;
    int var3 =5;
    var t =  new Test
    {
        Test1 = var1.GetValueOrDefault(),
        Test2 = var2,
        Test3 = var3
    };

The default value of Test1 is zero so you could use the null-coallescing operator: Test1的默认值为零,因此您可以使用null-coallescing运算符:

var t =  new Test {
    Test1 = var1 ?? 0,
    Test2 = var2,
    Test3 = var3
};

If the class might specify a default besides the default int, or for another reason you need to not call the property setter at all when var1 is null , then you can't use the object initialization syntax for Test1 . 如果该类除默认int之外还可以指定其他默认值,或者由于其他原因,当var1null时根本不需要调用属性设置器,那么您就不能对Test1使用对象初始化语法。 (I'm aware that the question says to use object initialization, but just in case that can't work...) Eg (我知道这个问题说要使用对象初始化,但以防万一无法使用...)

public class Test
{
    public int Test1 { get; set; }
    public int Test2 { get; set; }
    public int Test3 { get; set; }

    public Test()
    {
        Test1 = -1;
    }
}

var t =  new Test
    {
        Test2 = var2,
        Test3 = var3
    };
if (var1 != null) // or (var1.HasValue)
    t.Test1 = var1.Value;

If this isn't the case, you might go with this or any other answer. 如果不是这种情况,则可以选择此答案或任何其他答案。

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

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