How to make a method generic when "type 'T' must be a reference type"?

Dav*_*Dev 78 c# generics nhibernate

Possible Duplicate:
Why do I get “error: … must be a reference type” in my C# generic method?

I have 2 Repository methods that are almost identical:

public IList<Fund> GetFundsByName(int pageSize, string searchExpression)
{
    return _session.CreateCriteria<Fund>()
        .AddNameSearchCriteria<Fund>(searchExpression)
        .AddOrder<Fund>(f => f.Name, Order.Asc)
        .SetMaxResults(pageSize).List<Fund>();
}

public IList<Company> GetCompaniesByName(int pageSize, string searchExpression)
{
    return _session.CreateCriteria<Company>()
        .AddNameSearchCriteria<Company>(searchExpression)
        .AddOrder<Company>(f => f.Name, Order.Asc)
        .SetMaxResults(pageSize).List<Company>();
}
Run Code Online (Sandbox Code Playgroud)

The only difference is that the first one's _session.CreateCriteria is of type Fund and the second one is company

I was hoping that I could make this generic by changing the method definition to:

public IList<T> GetEntitiesByName<T>(int pageSize, string searchExpression)
    where T : ISearchableEntity
{
    return _session.CreateCriteria<T>()
        .AddNameSearchCriteria<T>(searchExpression)
        .AddOrder<T>(f => f.Name, Order.Asc)
        .SetMaxResults(pageSize).List<T>();
}
Run Code Online (Sandbox Code Playgroud)

where ISearchableEntity is defined as:

public interface ISearchableEntity
{
    string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

but unfortunately NHibernate doesn't like this and gives me the error:

The type 'T' must be a reference type in order to use it as parameter 'T' in the generic type or method 'NHibernate.ISession.CreateCriteria<T>()'

Is it possible for me to make this generic some other way?

Mar*_*ers 201

You could try adding the constraint class:

where T : class, ISearchableEntity
Run Code Online (Sandbox Code Playgroud)

  • 起初我假设这只有在T必须是Class的情况下才有效,但在查看了burningmonk的答案中链接的页面后,我发现尽管有这个约束的名称,"这也适用于任何类,接口,委托或数组类型." 所以使用`where T:class`,即使你需要T作为接口,就像我的情况一样. (3认同)

the*_*onk 29

以下是您可以在T上使用的完整约束列表

http://msdn.microsoft.com/en-us/library/d5x73970.aspx