【问题标题】:Convert array type to singular将数组类型转换为单数
【发布时间】:2017-09-20 17:28:07
【问题描述】:

在 C# 中是否可以将数组类型转换为单数类型 - 以与 Activator.CreateInstance 一起使用。以此为例:

void Main()
{
    var types = new[] { typeof(ExampleClass), typeof(ExampleClass[]) };
    var objects = new List<object>();

    foreach (var type in types)
    {
        // possibly convert type here? (from array to singular - type[] to type) 

        Debug.WriteLine($"{type}");
        objects.Add(Activator.CreateInstance(type));
    }
}

// Define other methods and classes here

public class ExampleClass
{
    public int X;
    public int Y;
}

得到以下输出:

【问题讨论】:

  • 你想退回什么?一个元素为零的数组?一个元素的数组?数组元素类型的实例?还有什么?
  • 如果我错了,请纠正我,但您的代码与您的问题无关。您正在询问转换数组类型,但在代码中您只是试图创建一个新数组(使用反射),但由于您没有向数组构造函数提供参数而失败 - 您的数组的大小'正在尝试创建。

标签: c# activator


【解决方案1】:

如果我正确理解您的问题,您可能希望通过反射使用 Type.GetElementType() 进行类似的操作。

static void Main(string[] args)
    {

        var types = new[] { typeof(ExampleClass), typeof(ExampleClass[]) };
        var objects = new List<object>();

        foreach (var type in types)
        {
            var typeInstance = type.GetElementType();

            if (typeInstance != null)
            {
                Debug.WriteLine($"{typeInstance}");
                objects.Add(Activator.CreateInstance(typeInstance));
            }
            else
            {
                objects.Add(Activator.CreateInstance(type));
            }
        }
    }

   public class ExampleClass
   {
        public int X;
        public int Y;
   }

【讨论】:

    【解决方案2】:

    如果我正确理解了您的问题,您想获取数组的基本类型,对吗?使用该类型的 IsArray 属性应该很容易,只需像这样检查列表中的每个条目:

    private static Type GetTypeOrElementType(Type type)
    {
        if (!type.IsArray)
            return type;
    
        return type.GetElementType();
    }
    

    顺便说一句,如果你想创建一个特定类型的新数组,你可以使用Array.CreateInstance而不是Activator.CreateInstance

    【讨论】:

      【解决方案3】:

      发现这行得通:

      void Main()
      {
          var types = new[] { typeof(ExampleClass), typeof(ExampleClass[]) };
          var objects = new List<object>();
      
          foreach (var type in types)
          {
              Debug.WriteLine($"{type}");
              objects.Add(type.IsArray
                          ? Activator.CreateInstance(type, 1)
                          : Activator.CreateInstance(type));
          }
      }
      
      // Define other methods and classes here
      
      public class ExampleClass
      {
          public int X;
          public int Y;
      }
      

      【讨论】:

        猜你喜欢
        • 2013-05-01
        • 1970-01-01
        • 2011-02-01
        • 1970-01-01
        • 2021-09-09
        • 2017-05-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多