将动态转换为泛型

时间:2017-06-05 15:03:57

标签: c# generics casting

我有以下内容:

public static IEnumerable<DynamicAttributeValue<T>> Read<T>(EntityType entityType, long entityId, string shortName, OptionSearch optionSearch = OptionSearch.Name)
{
    if (typeof(T) == typeof(object))
    {
        return Read(entityType, entityId, shortName, optionSearch);
    }

    return ReadWithOptions<T>(entityType, entityId, shortName, optionSearch).Values;
}

public static IEnumerable<DynamicAttributeValue<dynamic>> Read(EntityType entityType, long entityId, string shortName, OptionSearch optionSearch = OptionSearch.Name)
{
    var datatype = GetDefinition(shortName, entityType).DataType;
    switch (datatype)
    {
        case DataType.MultipleChoice:
            throw new NotSupportedException("Multiple choice attributes are not supported.");
        case DataType.Integer:
            return (dynamic)ReadWithOptions<int>(entityType, entityId, shortName, optionSearch).Values;
        case DataType.Text:
            return (dynamic)ReadWithOptions<string>(entityType, entityId, shortName, optionSearch).Values;
        case DataType.Bit:
            return (dynamic)ReadWithOptions<bool>(entityType, entityId, shortName, optionSearch).Values;
        case DataType.Decimal:
            return (dynamic)ReadWithOptions<decimal>(entityType, entityId, shortName, optionSearch).Values;
        case DataType.BigInt:
            return (dynamic)ReadWithOptions<long>(entityType, entityId, shortName, optionSearch).Values;
        case DataType.Float:
            return (dynamic)ReadWithOptions<float>(entityType, entityId, shortName, optionSearch).Values;
        default:
            throw new ArgumentOutOfRangeException();
    }
}

我试图使用Read()来提供特定的基础类型,如果它们在T中提供对象或动态。

但是我收到以下错误:

  

无法隐式转换类型   system.collections.generic.ienumerable<DynamicAttributeValue<dynamic>>   到system.collections.generic.ienumerable<DynamicAttributeValue<T>>。   存在明确的转换(您是否错过了演员?)

我迷失了如何施放基本上

的回报 当我知道T是对象或动态时,

IEnumerable<DynamicAttributeValue<int>>IEnumerable<DynamicAttributeValue<object>>IEnumerable<DynamicAttributeValue<dynamic>>

如果因为某些原因(例如Read<CustomObject>显然应该抛出运行时错误而尝试为其提供自定义对象),我可以抛出运行时错误。我只支持Read<dynamic>Read<object>

0 个答案:

没有答案