简体   繁体   English

在运行时将列表项转换为通用类型

[英]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 然后我有一个从该接口(通用)派生的类,例如,带有属性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> 要获得这些对象的列表,我正在使用List<IStorage>

The question is, how do I cast the item from the List to ManagingModel<> to access this property? 问题是,如何将项目从列表强制转换为ManagingModel<>以访问此属性?

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: 尝试通过索引将“ as”转换为给定模型:

    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. 如果强制转换后backToManagingModel为null,则将其强制转换为错误的类型,否则强制转换成功,您可以获取属性。

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 您无需检查所有类型,只需调用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> . 由于Func<T>的值用于视图,因此您可以扩展IStorage以将其作为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();
        }
    }
}

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

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