简体   繁体   中英

Casting “value” in C# property as a IEnumerable<> generic in DataSource override

Here is your basic DataSource override:

    public override object DataSource
    {
        get
        {
            return base.DataSource;
        }
        set
        {   
            base.DataSource = value;
        }
    }

What I would like to do in the setter method is cast value to IEnumerable<> and do some manipulations on it (or throw an exception if I can't cast it to IEnumerable<> ) and then pass that into base.DataSource . Any help in accomplishing this would be appreciated.

You didn't mention .net version, but linq provides a AsEnumerable() method that does what you are looking for.

The useage would be value .AsEnumerable< type >()

See here

public override object DataSource
{
    get
    {
        return base.DataSource;
    }
    set
    {   
        if (!(value is IEnumerable<MyType>))
            throw new InvalidOperationException(...); // or ArgumentException

        base.DataSource = (IEnumerable<MyType>) value;
    }
}

or perhaps...

    set
    {
        // Includes IEnumerable<T> for any T
        if (!(value is IEnumerable))
            throw new InvalidOperationException(...); // or ArgumentException

        // Do some processing on it, for example cast to your type?
        base.DataSource = ((IEnumerable) value).Cast<MyType>();
    }

You can get by with a simple type cast, as shown with several examples below. Note that you should be cautious entering into just any IEnumerable, as some enumerable classes have no concept of backing up once iterated. Lists and arrays will treat you fine, but some others pass a point of no return with every iteration.

public override object DataSource
{
    get { return base.DataSource; }
    set
    {   
        // Throws an exception if the cast won't work.
        var genenum = (IEnumerable<string>)value;

        // Non-generic enumerable collection, if generic is not necessary.
        // Still throws an exception if the cast is invalid.
        var nongenenum = (IEnumerable)value;

        // Alternatively, you can use a defensive type cast, and manually
        // throw an exception if the result is null or not able to be casted.
        var safeenum = value as IEnumerable<string>;
        if(safeenum == null) throw new ArgumentException();

        // or...
        if(!(value is IEnumerable<string>)) throw new ArgumentException();

        // ... Do stuff with the enumerable.

        base.DataSource = value;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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