Pergunta

Possible Duplicate:
.NET: Determine the type of “this” class in its static method

Hello is there any way to call non-static GetType() in non-static class without using typeof()?

Here is example of my code that I'm working on.

private static ISession GetOrCreate(ISessionFactory factory)
{
    if (HttpContext.Current!=null)
    {
        ISession session = GetExistingWebSession();
        if (session == null)
        {
            session = OpenSessionAndAddToContext(factory);
        }
        else if (!session.IsOpen)
        {
            session = OpenSessionAndAddToContext(factory);
        }            return session;
    }
}

private ISession GetExistingWebSession()
{
    return HttpContext.Current.Items[GetType().FullName] as ISession;
}
Foi útil?

Solução

You can't call an instance method from a static method like this. It makes no sense at all.

Read more about static and instance methods on MSDN:

What's wrong with the typeof()?

Outras dicas

typeof() is a compile-time method. You call it against a particular type.

GetType() is a run-time method. You call it against a particular instance. If class (type) is static, you can't get its instance, thus call the method.

You can't use "this" in a static method, whether the class is static or nonstatic. Why don't you want to use typeof? It's perfectly reasonable in this case, since you always know the containing class in a static method. The only reason to use GetType() is when there's a possibility that it's called in a derived class.

Yes you can call the GetType method from with GetExistingWebSession as it is a non static method.

However your problem is actually that you cannot call GetExistingWebSession from within GetOrCreate

You need some method to create an instance of your class that you can then use.

e.g.

MyClass c=new MyClass();
ISession session = c.GetExistingWebSession(); 
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top