【问题标题】:How can I observe the value type of an array?如何观察数组的值类型?
【发布时间】:2018-03-16 00:34:25
【问题描述】:

我有一个方法可以检查对象的Type 以确定它是否复杂:

private static bool IsComplexObject(Type type)
{
    if (IsNullable(type))
    {
        // nullable type, check if the nested type is simple
        return IsComplexObject(type.GetGenericArguments()[0]);
    }

    if (type.Equals(typeof(string)))
    {
        return false;
    }
    if (type.Equals(typeof(decimal)))
    {
        return false;
    }
    if (type.Equals(typeof(DataTable)))
    {
        return false;
    }
    if (type.IsValueType)
    {
        return false;
    }
    if (type.IsPrimitive)
    {
        return false;
    }
    if (type.IsEnum)
    {
        return false;
    }

    return true;
}

问题是:当我有一个简单类型数组的Type,例如Int32[],我的方法返回true

我可以通过将这个if 语句添加到我的方法中来防止这种情况发生:

if (type.IsArray)
{
    return false;
}

问题是这个if 语句会阻止识别实际的复杂对象。例如,以下设置确定自定义类不复杂:

public class TestClass
{ 
    public void TestComplexArray()
    {
        var result = IsComplexObject(typeof(MyComplexClass[]));

        // result == false
    }
}

public class MyComplexClass
{
    public string Name { get; set; }
    public string Id { get; set; }
}

所以我的问题是:如何检查数组值类型的复杂性以将 Int32[]MyComplexClass[] 分开?

【问题讨论】:

  • 您对“复杂类型”的定义是什么? (我在 Wikipedia en.wikipedia.org/wiki/Complex_data_type | en.wikipedia.org/wiki/Composite_data_type 上只找到了部分定义)。你是说所有的课吗?好吧,任何类都可以被赋予索引器,因此它就像一个数组 (docs.microsoft.com/en-us/dotnet/csharp/programming-guide/…),所以它并不是一个简单的排除。事实上,数组就是类。
  • 我对复杂类的定义在我的IsComplexObject 方法中进行了概述。该方法可以准确地识别我对复杂对象的定义,除了数组类型之外。
  • 你试过Type.GetElementType()吗?这很疯狂,它可能会起作用。
  • stackoverflow.com/questions/840878/… 应该可以帮助你做你想做的事。
  • 我确实想知道你想要这个做什么...特别是我想知道为什么所有值类型都被认为不复杂,因为它们实际上可能非常复杂并且包含许多嵌套项。我的意思是,我不是 100% 确定您是否真的希望 public struct MyStruct{ public MyComplexClass Stuff {get; set;} } 被视为不复杂的(尽管您可能这样做,但我不是通灵者)。

标签: c# reflection


【解决方案1】:

尝试检索元素类型,然后递归调用IsComplexObject,如下所示:

if (type.IsArray) return IsComplexObject(type.GetElementType());

对于“复杂对象”数组(不符合代码中指定条件的对象),这应该返回 true。请注意,对于复杂对象数组的数组或数组数组的数组,它也会返回 true。如果这是一个问题,您可以进行更改,使其仅递归一次,如下所示:

private static bool IsComplexObject(Type type, bool recurse = true)
{
    if (type.IsArray) return 
    (
        recurse
        ? IsComplexObject(type.GetElementType(), false) 
        : false
    );
    //etc.

【讨论】:

    【解决方案2】:

    也许您想检查数组排名,并在元素类型上重复?

    if (type.IsArray)
    {
        if (type.GetArrayRank() != 1)
        {
            return true;
        }
    
        Type elementType = type.GetElementType();
    
        if (elementType.IsArray)
        {
            return true;
        }
    
        return IsComplexType(elementType);
    }
    

    【讨论】:

      猜你喜欢
      • 2021-05-04
      • 2016-08-05
      • 1970-01-01
      • 2019-06-04
      • 2021-12-30
      • 2018-06-20
      • 1970-01-01
      • 2020-02-27
      • 2011-07-03
      相关资源
      最近更新 更多