如何将字符串转换为通用类型

丽贝卡

我有一个签名如下的方法:

public IList<T> GetReferenceData<T>(TransactionManager transactionManager = null)
{
    IList<T> collection;
    var cacheData = DataCacheManager.Instance.GetCacheItem(typeof(T).Name);
    if (cacheData != null)
    {
        collection = (IList<T>)cacheData;
    }
    else
    {
        collection = this.GetReferenceDataNoCache<T>(transactionManager);
        DataCacheManager.Instance.AddCacheItem(typeof(T).Name, collection);
    }

    return collection;
}

我有另一种方法可以让我传递一个字符串,该字符串将该字符串转换为适当的类型。然后,我想调用上述方法。

public IList GetReferenceDataByType(string referenceType)
{
        // this works and returns the appropriate type correctly
        var type = this.GetEntity(referenceType); 

        // now I'm stuck
        return this.GetReferenceData<?>();
}

用什么代替问号?

马格努斯

如果我正确理解了您的问题,那么您需要执行以下操作:

public IList GetReferenceDataByType(string referenceType)
{
        // this works and returns the appropriate type correctly
        var type = this.GetEntity(referenceType); 

        var method = this.GetType().GetMethod("GetReferenceData");
        var generic = method.MakeGenericMethod(type);
        return (IList) generic.Invoke(this, new object[] { null });
}

请注意,该方法IList<T>未实现,IList因此强制转换可能会失败。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章