如何检查对象是否是某种类型的数组?

发布于 2024-10-21 07:44:26 字数 452 浏览 2 评论 0原文

这工作正常:

var expectedType = typeof(string);
object value = "...";
if (value.GetType().IsAssignableFrom(expectedType))
{
     ...
}

但是如何在不将 expectedType 设置为 typeof(string[]) 的情况下检查 value 是否为字符串数组?我想做一些类似的事情:

var expectedType = typeof(string);
object value = new[] {"...", "---"};
if (value.GetType().IsArrayOf(expectedType)) // <---
{
     ...
}

这可能吗?

This works fine:

var expectedType = typeof(string);
object value = "...";
if (value.GetType().IsAssignableFrom(expectedType))
{
     ...
}

But how do I check if value is a string array without setting expectedType to typeof(string[])? I want to do something like:

var expectedType = typeof(string);
object value = new[] {"...", "---"};
if (value.GetType().IsArrayOf(expectedType)) // <---
{
     ...
}

Is this possible?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

夜光 2024-10-28 07:44:26

使用 Type.IsArrayType.GetElementType() 检查数组的元素类型。

Type valueType = value.GetType();
if (valueType.IsArray && expectedType.IsAssignableFrom(valueType.GetElementType())
{
 ...
}

但要注意 Type.IsAssignableFrom()!如果您想检查完全匹配,则应该检查是否相等(即typeA == typeB)。如果您想检查给定类型本身是否是类型本身子类/接口,那么您应该使用Type.IsAssignableFrom()

typeof(BaseClass).IsAssignableFrom(typeof(ExpectedSubclass))

Use Type.IsArray and Type.GetElementType() to check the element type of an array.

Type valueType = value.GetType();
if (valueType.IsArray && expectedType.IsAssignableFrom(valueType.GetElementType())
{
 ...
}

But beware of Type.IsAssignableFrom()! If you want to check for an exact match, you should check for equality (i.e. typeA == typeB). If you want to check if a given type is the type itself or a subclass/interface, then you should use Type.IsAssignableFrom():

typeof(BaseClass).IsAssignableFrom(typeof(ExpectedSubclass))
将军与妓 2024-10-28 07:44:26

您可以使用扩展方法(不是必须这样做,而是使其更具可读性):

public static class TypeExtensions
{
    public static bool IsArrayOf<T>(this Type type)
    {
         return type == typeof (T[]);
    }
} 

然后使用:

Console.WriteLine(new string[0].GetType().IsArrayOf<string>());

You can use extension methods (not that you have to but makes it more readable):

public static class TypeExtensions
{
    public static bool IsArrayOf<T>(this Type type)
    {
         return type == typeof (T[]);
    }
} 

And then use:

Console.WriteLine(new string[0].GetType().IsArrayOf<string>());
猥琐帝 2024-10-28 07:44:26

最简洁、最安全的方法是使用 MakeArrayType:

var expectedType = typeof(string);
object value = new[] {"...", "---"};
if (value.GetType() == expectedType.MakeArrayType())
{
     ...
}

The neatest and securest way to do it that found is using MakeArrayType:

var expectedType = typeof(string);
object value = new[] {"...", "---"};
if (value.GetType() == expectedType.MakeArrayType())
{
     ...
}
掀纱窥君容 2024-10-28 07:44:26
value.GetType().GetElementType() == typeof(string)

作为额外的好处(但我不是 100% 确定。这是我使用的代码...)

var ienum = value.GetType().GetInterface("IEnumerable`1");

if (ienum != null) {
    var baseTypeForIEnum = ienum.GetGenericArguments()[0]
}

有了这个,您可以查找 List、IEnumerable... 并获取 T。

value.GetType().GetElementType() == typeof(string)

as an added bonus (but I'm not 100% sure. This is the code I use...)

var ienum = value.GetType().GetInterface("IEnumerable`1");

if (ienum != null) {
    var baseTypeForIEnum = ienum.GetGenericArguments()[0]
}

with this you can look for List, IEnumerable... and get the T.

情域 2024-10-28 07:44:26

这是另一个样本,

using System;
using System.Collections.Generic;

public static class Program
{
    public static void Main()
    {
        Type type = typeof(string[]);
        // string[], int[], char[], List<MyData>, IList<MyData>, IEnumarable<MyData>  =====> console write "True",
        // string, int, MyData etc ==== does not write 
        
        if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IList<>))
        {
            Type itemType = type.GetGenericArguments()[0];
            Console.WriteLine("True");
        }

        if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>))
        {
            Type itemType = type.GetGenericArguments()[0];
            Console.WriteLine("True");
        }

        if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IEnumerable<>))
        {
            Type itemType = type.GetGenericArguments()[0];
            Console.WriteLine("True");
        }
        
        if (type.IsArray)
        {
            Console.WriteLine("True");
        }       
    }
}

public class MyData
{
    public string Name { get; set; }
}

This is another sample,

using System;
using System.Collections.Generic;

public static class Program
{
    public static void Main()
    {
        Type type = typeof(string[]);
        // string[], int[], char[], List<MyData>, IList<MyData>, IEnumarable<MyData>  =====> console write "True",
        // string, int, MyData etc ==== does not write 
        
        if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IList<>))
        {
            Type itemType = type.GetGenericArguments()[0];
            Console.WriteLine("True");
        }

        if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>))
        {
            Type itemType = type.GetGenericArguments()[0];
            Console.WriteLine("True");
        }

        if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IEnumerable<>))
        {
            Type itemType = type.GetGenericArguments()[0];
            Console.WriteLine("True");
        }
        
        if (type.IsArray)
        {
            Console.WriteLine("True");
        }       
    }
}

public class MyData
{
    public string Name { get; set; }
}
旧街凉风 2024-10-28 07:44:26

您实际上需要知道数组的类型吗?或者您只需要元素属于某种类型?

如果是后者,您可以简单地过滤仅与您想要的匹配的元素:

string[] strings = array.OfType<string>();

Do you actually need to know the type of the array? Or do you only need the elements to be of a certain type?

If the latter, you can simply filter only the elements that match what you want:

string[] strings = array.OfType<string>();
枉心 2024-10-28 07:44:26
if(objVal.GetType().Name == "Object[]")

对于数组为真

if(objVal.GetType().Name == "Object[]")

true for array

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文