1

可能重复:
.NET:在其静态方法中确定“this”类的类型

您好,有什么方法可以GetType()在非静态类中调用非静态而不使用typeof()

这是我正在处理的代码示例。

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;
}
4

4 回答 4

4

您不能像这样从静态方法调用实例方法。这根本没有意义。

在 MSDN 上阅读有关静态和实例方法的更多信息:

有什么问题typeof()

于 2012-04-12T09:19:25.050 回答
2

typeof()是一种编译时方法。您将其称为针对特定类型的。

GetType()是一种运行时方法。您针对特定实例调用它。如果类(类型)是静态的,则无法获取其实例,因此调用该方法。

于 2012-04-12T09:23:08.310 回答
0

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(); 
于 2012-04-12T09:26:23.003 回答
0

无论类是静态的还是非静态的,都不能在静态方法中使用“this”。为什么不想使用 typeof?在这种情况下这是完全合理的,因为您总是知道静态方法中的包含类。使用 GetType() 的唯一原因是有可能在派生类中调用它。

于 2012-04-12T09:21:59.573 回答