【问题标题】:cannot initialize type with a collection initializer无法使用集合初始化程序初始化类型
【发布时间】:2023-03-18 15:34:02
【问题描述】:

我有一个类选项。

public class Option
{                
    public bool Aggregation { get; set; }
    public PropertyOptions Property { get; set; }
    public bool DoEvent { get; set; }
}

PropertyOptions 是这样的..

public enum PropertyOptions
{        
    [EnumMember]
    On = 0,     
    [EnumMember]
    Off = 1,
    [EnumMember]        
    Auto = 2,
}

现在我有一个返回类 Option 对象的方法

Option setOptions()
{
        return new Option()
        {
            Aggregation = true,                
            Property = new PropertyOptions()
            {
                PropertyOptions.Auto,
            },                                       
            DoEvent = true,
       };
}

这里我收到一条错误消息“无法使用集合初始化程序初始化类型 PropertyOptions,因为它没有实现 System.Collection.IEnumerable”

我不确定如何设置数据成员“属性”。 如果有人能引起我的注意可能是什么错误以及如何纠正它,那将会很有帮助?

【问题讨论】:

    标签: c#


    【解决方案1】:

    你需要使用正则赋值。

    new Option()
    {
        Aggregation = true,                
        Property = PropertyOptions.Auto,                                   
        DoEvent = true
    }
    

    您尝试使用的语法是用于集合初始化。例如:

    var list = new List<string>
    {
        "apple",
        "banana"
    };
    

    您的 Property 属性不是集合。

    【讨论】:

      【解决方案2】:

      New 运算符用于从类中实例化对象。您正在使用一个枚举,它不是一个类。

      你应该可以只使用赋值运算符。

      new Option()
      {
          Aggregation = true,                
          Property = PropertyOptions.Auto,                                   
          DoEvent = true
      };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-21
        • 2017-08-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多