开发者

ASP.NET MVC/C# - Type casting to an array in a custom required validation attribute

I'm attempting to create a custom required validation attribute which will be able to take in a 1d array of any size and verify that at least one element is not null/empty string. I'm having some trouble figuring out how to turn the incoming generic object into an array. Here's what I have so far:

public class RequiredArrayAttribute : RequiredAttribute
{
    public override bool IsValid(object value)
    {
        var valueType = value.GetType();

        if (!valueType.IsArray)
        {
            return false;
        }

        bool hasValue = false;

        foreach (var item in value)
        {
            /* if (item != null/empty)
             * {
     开发者_C百科        *    hasValue = true;
             * }
            */
        }

        return hasValue;
    }
}

While my specific use case in this instance will be dealing with string[], I'd like to keep the attribute as generic as possible for future use in other projects. Any ideas on how to proceed?

EDIT:

I basically need to do something like:

foreach (var item in (valueType[])value)
{
    // ...
}

But I'm not sure how/if it's possible to dynamically cast to an array like that.


i believe you need following: generic handeling of your loop: check answer below

C# Syntax - Example of a Lambda Expression - ForEach() over Generic List

Cast as T:

you can create separate class that will represent T

eg: public class Foo{ public string Boo{get;set;} }

and after you put it into List list = new List() etc:)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜