简体   繁体   中英

generics in method, c#

This is my first question so be gentle :)

I want to be able to use method for generic types which will return me object for later use. I have tried the code below but it's not complete.

I need this to call like this: City city = GetDataById(Id); Of course instead of city I need generic use. Thanks and regards.

private T GetDataById(Guid Id)
        {
            T obj;
            using (ISession session = Session.OpenSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    obj = session.Get<T>(Id);
                    tx.Commit();                    
                }    
                 return obj;
            }

        }

I think that you want:

    private T GetDataById<T>(Guid Id)
    {
        T obj;
        using (ISession session = Session.OpenSession())
        {
            using (ITransaction transaction = session.BeginTransaction())
            {
                obj = session.Get<T>(Id);
                tx.Commit();
            }
            return obj;
        }
    }

then call it as:

        City city = GetDataById<City>(Id);

You never define T. You... need to.

private T GetDataById<T>(Guid Id) { /* ... */ }

And...

City city = GetDataById(Id);

You'll never be able to call it like that because the type argument cannot be inferred. You will need to supply it, ie,

City city = GetDataById<City>(Id);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM