尝试从List <string>创建自定义类型的实例。两者都继承自System.Collections.Generic.List <string> </string> </string>

时间:2013-03-02 02:17:49

标签: c# string list collections

我有第三方Web API,它使用名为ArrayOfString的自定义类型,该类型继承自System.Collections.Generic.List。我正在尝试编写将动态生成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个参数的构造函数,但是我不确定如何初始化自定义类型。任何帮助或建议将不胜感激。

1 个答案:

答案 0 :(得分:0)

我不想让这个问题没有答案。 我开发的最终基类看起来像这样。

再次感谢您的帮助。

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
  }
}