Why Can't I Use TEntity?
It seems like the most simplistic things are hard to figure out sometimes... Many code references have the type TEntity used for generic handling of entities in an entity data model. I tried to use it in my code and get: "Unknown type 'TEntity'" what gives??? Why do I get "Unknown type"? Is this only available in .net 4.0?
BTW: Using .net 3.5.
I'm trying to use code from this book:
public TEntity ExecuteFirstorDefa开发者_运维问答ult<TEntity>(ObjectQuery<TEntity> objectQuery)
{
try
{
return objectQuery.FirstOrDefault();
}
catch (EntitySqlException ex)
{
throw ex; //TODO: Replace with handling code
//additional exceptions as described in Chapter 18
}
}
TEntity
is a generic type parameter, not a concrete type.
I guess my question is why I can't use it, why do I get Unknown type.
Because it's not a concrete type.
Say you have a generic list implementation, declared as List<T>
. T
is a type parameter, which means that it does not represent a specific type. As the programmer, you have to instruct the compiler to use a specific type to use, rather than the generic type T
, by providing a type argument. You could create a list of integers like so:
List<int> myInts = new List<int>();
In this example, the type argument is int
. All the generic methods (or properties) of List
that accept or return a T
will instead use int
.
Further reading
- An Introduction to C# Generics
- Generics (C# Programming Guide)
精彩评论