#if 区域不工作

#if region does not work

我想使用 #if 语句在 val2 为真时跳过序列化 val 并在 val2 为假时序列化 val。但是我的代码似乎不起作用:

#if val2
    [XmlIgnore]
#else   
    [XmlElement(ElementName = "val")]
#endif
public bool val
{
    { get; set; } = false;
}

[XmlElement(ElementName = "val2")]
public bool val2
{
    { get; set; } = true;
}

我需要做什么才能让它正常工作?谢谢

我认为您需要定义要使用 #define 测试的交易品种。这些是预处理器指令,您不能使用正常的 属性 名称等,因为它们在编译过程中发挥作用,发生在预处理之后。

这是来自标准:

Evaluation of a pre-processing expression always yields a boolean value. The rules of evaluation for a pre-processing expression are the same as those for a constant expression (§7.19), except that the only user-defined entities that can be referenced are conditional compilation symbols.

正如 this question 中指出的那样,您需要这样的东西:

public class Item
{
    public bool val { get; set; }

    public bool ShouldSerializeval()
    {
       return !val2;
    }

    [XmlElement(ElementName = "val2")]
    public bool val2 { get; set; }  
}

void Main()
{
    Item item = new Item(){val=true, val2=true};

    XmlSerializer xs = new XmlSerializer(typeof(Item));
    StringWriter sw = new StringWriter();
    xs.Serialize(sw, item);
    sw.ToString();
}

只需将以下内容之一添加到您的代码中,当 val2 为真时,val 将不会被序列化:

public bool ShouldSerializeval()
{
    return val2 == false;
}

public bool ShouldSerializeval()
{
    return !val2;
}