简体   繁体   中英

Cast list item to generic type at runtime

I have a following interface:

interface IStorage
{ }

and then I have a class that derives from this interface (which is generic) with, for example, with a property Get

public class ManagingModel<T> : IStorage
{
    public Func<T> Get { get; set; }
}

To have a list of those objects, I'm using the List<IStorage>

The question is, how do I cast the item from the List to ManagingModel<> to access this property?

For example you can access list element by index. Example:

    var managingString = new ManagingModel<string>();
    var managingInt = new ManagingModel<int>();
    var managingDouble = new ManagingModel<double>();

    var list = new List<IStorage>();

    list.Add(managingString);
    list.Add(managingInt);
    list.Add(managingDouble);

Trying to cast "as" given model via index:

    var backToManagingModel = list[1] as ManagingModel<int>;

    if (backToManagingModel != null)
    {
        var get = backToManagingModel.Get;
    }

If backToManagingModel is null after casting, then it's being casted to wrong type, otherwise casting is sucessful and you can get your property.

Edit: What about not using generics at all, but simply use object?

    public static string GetString()
    {
        return "xyz";
    }

    public interface IStorage
    {
        Func<object> Get { get; set; }
    }

    public class ManagingModel : IStorage
    {
        public Func<object> Get { get; set; }
    }

You won't need to check all the types, just call list[index].Get

        var managingString = new ManagingModel
        {
            Get = new Func<string>(GetString)
        };

        var list = new List<IStorage>();

        list.Add(managingString);

        var get = list[1].Get;

Since the value of the Func<T> is going to a view then you probably can extend IStorage to do it as a Func<object> .

Try this:

interface IStorage
{
    Func<object> Get { get; }
}

public class ManagingModel<T> : IStorage
{
    public Func<T> Get { get; set; }

    Func<object> IStorage.Get
    {
        get
        {
            return () => this.Get();
        }
    }
}

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