问题
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
MamConfigurationto typeT
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