简体   繁体   English

如果数组包含特定类,您如何询问它?

[英]How do you ask an array if it contains a Specific class?

I am trying to create a "Mario" video game, and in order to obtain intersecting objects, our teacher provided us with an example demonstration, which allows the object to detect if it is touching EXACTLY one other object, and the first object that the method finds, is returned. 我正在尝试创建一个“马里奥”视频游戏,为了获得相交的对象,我们的老师为我们提供了一个示例演示,它允许对象检测它是否正在接触另一个对象,并且第一个对象是方法查找,返回。 I am trying, instead to return an array of every object that the current object is currently touching. 我正在尝试,而是返回当前对象当前正在触摸的每个对象的数组。 I was capable of returning an array of every object currently touching it, but now I need an easy/efficient way to check if the array contains an object of a required type, such as 我能够返回当前触及它的每个对象的数组,但现在我需要一种简单/有效的方法来检查数组是否包含所需类型的对象,例如

if (array.Contains(Mario))
    {
    //Do Work here
    }

The array that is being checked if it Contains(Mario), is the returned array of the intersecting Sprites, but when I ask if it actually contains objects of type Mario, it says "Error 14 'WindowsGame10.Mario' is a 'type' but is used like a 'variable' ". 正在检查的数组是否包含(Mario),是相交Sprite的返回数组,但是当我问它是否实际包含Mario类型的对象时,它会显示“Error 14'WindowsGame10.Mario'是'type'但用作'变量'“。 I Know I could do this with a for loop, and ask each individual index within the array if (array[i].GetType() == typeof(Mario)) , but for the amount of times I would need to perform this check within the code, and retype the same code over and over again, I feel that I need to learn a more efficient way to perform this. 我知道我可以使用for循环执行此操作,并询问数组中的每个索引if (array[i].GetType() == typeof(Mario)) ,但是我需要执行此检查的次数在代码中,并一遍又一遍地重新键入相同的代码,我觉得我需要学习一种更有效的方法来执行此操作。 I am in my first year of Computer Programming, and I am working with C# XNA, and I need to have some solution that I can understand. 我是计算机程序设计的第一年,我正在使用C#XNA,我需要一些我能理解的解决方案。 If there is a better way to do this, please let me know. 如果有更好的方法,请告诉我。

You can use LINQ's OfType() and Any() methods: 您可以使用LINQ的OfType()Any()方法:

if (array.OfType<Mario>().Any())
{

Using Linq you can do: 使用Linq你可以做到:

var marios = array.OfType<Mario>();
if (marios.Any())
{
     //Stuff
}

if you just need to know if there is any Mario then 如果你只是需要知道是否有任何马里奥

if(array.Any(a=>a is Mario))
{
}

this will break out of the iteration as soon it finds the first match. 一旦找到第一个匹配,这将突破迭代。

The Linq answers are great. Linq的答案很棒。 Just to provide an alternative approach, you could define an extension method like this: 只是为了提供一种替代方法,您可以定义一个这样的扩展方法:

static public bool ContainsType(this Array array, Type type)
{
    int len = array.Length; // Note that putting this in the loop is slightly slower
                            // because the compiler can't assume that a property value
                            // remains constant.
    for (int i = 0; i < len; i++)
    {
        if (array.GetValue(i).GetType() == type) return true;
    }

    return false;
}

that would be used like this: 会像这样使用:

    Array a = new object[] { "The meaning of life.", 42 };
    bool hasString = a.ContainsType(typeof(string)); // true
    bool hasInteger = a.ContainsType(typeof(int));  // true
    bool hasChar = a.ContainsType(typeof(char));  // false

Most straight forward way (without using LINQ) would be to use the is keyword: 最直接的方式(不使用LINQ)将使用is关键字:

foreach (Object obj in array)
{
    if (obj is Mario)
    {
        ...
    }
}

Update: If you need an exact Type match, and want to avoid code duplication, I think a rather simplistic extension method similar to this would be best - 更新:如果你需要一个确切的Type匹配,并希望避免代码重复,我认为一个相当简单的扩展方法类似于这将是最好的 -

public static bool ContainsType<T>(this T[] arr, Type type)
{
    for (int i = 0; i < arr.Length; i++)
        if (arr[i].GetType().Equals(type))
            return true;
    return false;
}

And the use - 并使用 -

if (array.ContainsType(typeof(Mario)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM