Cannot convert Type `ClassA` to T

匆匆过客 提交于 2021-01-29 09:08:45

问题


I'm writeing a generice method in C#:

private T GetMamConfigurations<T>(IDictionary<string, object> items,
                                  MaMDBEntities maMDBEntities) where T : class
{
    T geoConfigs = default(T);
    if (typeStr.Equals("MamConfiguration", StringComparison.OrdinalIgnoreCase))
    {
        geoConfigs = (T)GetGeoConfigurationNumericFromDB(items, maMDBEntities);
    }
    else if (typeStr.Equals("ListOfMamConfiguration", StringComparison.OrdinalIgnoreCase))
    {
        geoConfigs = (T)GetGeoConfigurationsPercentageFromDB(items, maMDBEntities);
    }

    return geoConfigs;
}

GetGeoConfigurationNumericFromDB returns MamConfiguration

whereas

GetGeoConfigurationsPercentageFromDB returns IList<MamConfiguration>

and I get compliation error:

cannot cast expression of type MamConfiguration to type T

Why is that?

Is there any way to solve without forcinf the two methods to return IList<MamConfiguration> ?


回答1:


Instead of using (T) to cast to T, you can use the as operator. as will return null if the conversion fails. If it succeeds, it will return your converted value.

geoConfigs = GetGeoConfigurationNumericFromDB(items, maMDBEntities) as T;



回答2:


Well, you can always placate the compiler by adding an object cast in the middle:

geoConfigs = (T)(object)GetGeoConfigurationNumericFromDB(items, maMDBEntities);

which will defer the type-check until runtime. However! There is no compiler way to do this otherwise, as it is never going to be happy with string tests like "MamConfiguration". Also, generics work well when the code is ... generic - i.e. does the same thing which each type. The code shown is the opposite of generic. It is non-generic code exposed through a generic API. It is always going to be messy inside. Personally I would try to avoid this usage in the first place.



来源:https://stackoverflow.com/questions/15762179/cannot-convert-type-classa-to-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!