开发者

Problem with Generics in C#

Fist of all, I'm new to generics. I have a problem with the following code:

namespace YvanSoftware_V5.Models
{
    public interface ISession : IDisposable
    {
        void CommitChanges();
        Db4objects.Db4o.IObjectContainer Container { get; }
        void Delete(System.Linq.Expressions.Expression<Func< T, bool>> expression);
        void Delete(object item);
        void DeleteAll();
        void Di开发者_StackOverflow中文版spose();
        T Single(System.Linq.Expressions.Expression<Func< T, bool>> expression);
        System.Linq.IQueryable All();
        void Save(T item);
    }
}

I get the following compilation error, but I don't know what it means in this context.

The type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference?)

I got this code from http://www.itslet.nl/?p=125 .

Thank you for your help,

Yvan


It's because T is not defined. The compiler will try to find a type named T, which does not exist. Try changing your interface signature to:

public interface ISession<T> : IDisposable

If you don't want the whole interface to be generic, you can add to each method, like:

Save<T>(T item)

In fact, that's what the author of this code does, look at his implementation class Db4oSession in the link you provided. The correct interface definition should be:

public interface ISession : IDisposable
{
    void CommitChanges();
    Db4objects.Db4o.IObjectContainer Container { get; }
    void Delete<T>(System.Linq.Expressions.Expression<Func< T, bool>> expression);
    void Delete(object item);
    void DeleteAll();
    void Dispose();
    T Single<T>(System.Linq.Expressions.Expression<Func< T, bool>> expression);
    System.Linq.IQueryable All();
    void Save<T>(T item);
}


You need to specify T as a template parameter on the generic functions like this:

 void Save<T>(T item);

I would start with something more simple for your first use of generics, though.


You need to define the type parameter T either on the interface or on the method:

public interface ISession<T> : IDisposable

or

void Delete<T>(System.Linq.Expressions.Expression<Func< T, bool>> expression)
T Single<T>(System.Linq.Expressions.Expression<Func< T, bool>> expression);
void Save<T>(T item);


Well, I am the writer of the article on Itslet. I just improved the code on the article. It seems that the syntax highlighter removed my <T> 's. Thanks for notifying.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜