c# generics, passing class
I just can't figure out how to write an equivalent interface in c#.
Java:
public interface DAO {
<T> T find(Class<T> c, Object key);
<T> List<T>开发者_如何学C; get(Class<T> c);
<T> void persist(T object);
}
This is my attempt so far in c#, problem is i need the Class to call the dataclassesdatacontext.GetTable<Class here>().ToList();
:
interface IDAO
{
T Find<T>(object key);
List<T> Get<T>(T c);
void Persist<T>(T obj);
}
I want to implement it like this:
public List<T> Get<T>()
{
return _dbx.GetTable<T>().ToList();
}
where _dbx is the dataclassdatacontext (linq to sql). But i get a red line under T which says: The type 'T' must be a reference type in order to use it as a parameter.
The generic parameter could be placed on the interface definition:
public interface IDAO<T>
{
T Find(object key);
List<T> Get(T c);
void Persist(T obj);
}
What you are looking for are Generic constraints. Namely you need to add where T : class
to methods with T parameter.
And like Darin Dimitrov said, it might be good idea to set type for whole interface, not every method. This will result in cleaner desing.
精彩评论