【问题标题】:Trying to create an instance of a custom type from List<string>. Both inherit from System.Collections.Generic.List<string>尝试从 List<string> 创建自定义类型的实例。两者都继承自 System.Collections.Generic.List<string>
【发布时间】:2013-02-16 16:13:09
【问题描述】:

我有一个第 3 方 Web API,它使用一个名为 ArrayOfString 的自定义类型,它继承自 System.Collections.Generic.List。我正在尝试编写将动态生成列表并返回 ArrayOfString 的方法,但是,我无法弄清楚如何正确执行此操作。

// Definition of ArrayOfString in API
public class ArrayOfString : System.Collections.Generic.List<string> {}


// Working Example with Static elements
public ArrayOfString GetPropertiesAsArrayOfString()
{
  ArrayOfString properties = new ArrayOfString()
  {
    "Name|String",
    "Description|String",  
    "InventoryLevel|Int32", 
    "Sku|String", 
    "UpdatedAt|DateTime" 
  };

  return properties;
}


// Trying to initialize the ArrayofString from a collection instead of from static strings. 

// Dynamically generated List<string>
List<string> items = new List<string>() { "Name|String", "Description|String", ect... };

ArrayOfString properties = new ArrayOfString(items)

上面的代码给出了一个错误,指出 ArrayOfString 不包含带有 1 个参数的构造函数,这是有道理的,但是我不确定如何初始化自定义类型。任何帮助或建议将不胜感激。

【问题讨论】:

  • 如果他们有一个有效的例子,你为什么不照着做呢?它向您展示了 C# 支持的集合初始化语法。否则,使用 Add to one item 或 AddRange 一次添加多个项目。它通过 List 基类获取这些方法。使用它们。
  • 如果它真的是一个数组,那它不起作用是有道理的。列表与数组不同,也许他们只是为了方便而选择了 IList 接口。如果 Array 有一个 AddRange 方法也可以工作。否则检查它是否具有设置数组“大小”的构造函数,然后只需对数组进行循环并手动设置数组中的字段,只需 3 行代码。
  • 非常感谢。 AddRange 方法有效。我在基类中使用一种方法将公共属性名称和类型映射到表列,这似乎是一个比在每个类中设置静态值更优雅的解决方案。再次感谢您的帮助。

标签: c# string list collections


【解决方案1】:

我不想让这个问题悬而未决。 我开发的最终基类如下所示。

再次感谢您的帮助。

public class BaseType
{
  public ArrayOfString GetPropertiesAsArrayOfString(Type type)
  {
    PropertyInfo[] propertyInfos = type.GetProperties();
    List<string> items = new List<string>();
    string propertyType = string.empty;

    for (int x = 0; x < propertyInfos.count(); x++)
    {

      switch propertyInfos[x].PropertyType.ToString())
      {
        case "System.String":
             propertyType = "String";
             break;
        case "System.DataTime":
             propertyType = "DateTime";
             break;
        case "System.Int32":
             propertyType = "Int32";
             break;
      }

      items.Add(propertyInfos[x].Name + "|" + propertyType);
    }

    ArrayOfString properties = new ArrayOfString();
    properties.AddRange(items);
    return properties
  }
}  

【讨论】:

    猜你喜欢
    • 2012-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-29
    • 2012-11-18
    • 2013-07-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多