【问题标题】:Does an instance method not create an object reference in c#实例方法是否不会在c#中创建对象引用
【发布时间】:2014-05-24 20:25:02
【问题描述】:

我正在使用 c# 开发一个 asp.net Web 应用程序。我有一个名为 GetUser 的公共课程。在那个类中,我有一个名为 GetCurrentUser 的方法。方法如下:

    public MobileUser GetCurrentUser(MDMDataContext dc, string userCode)
    {
        using (dc)
        {
            dc.ObjectTrackingEnabled = false;
            var currentUser =
                from MobileUser in dc.MobileUsers
                where MobileUser.UserCode == usercode                     
                select MobileUser;

            MobileUser mu = new MobileUser();
            mu = currentUser.Single();

            return mu;
        }
    }

但是当我尝试如下使用 GetCurrentUser 实例方法时:

using (MDMDataContext dc = new MDMDataContext())
        {
            GetUser.GetCurrentUser(dc, "ABCD");
        }

我收到以下错误,“非静态字段、方法或属性的对象引用'....GetUser.GetCurrentUser....'

但如果我在函数中添加 static 关键字,错误就会消失。有人可以为我揭开这个概念的神秘面纱吗?

【问题讨论】:

    标签: c# asp.net static-methods instance-methods


    【解决方案1】:

    你的方法是一个实例方法,这意味着你需要一个实例来运行它:

    using (MDMDataContext dc = new MDMDataContext())
    {
            GetUser user = new GetUser();
            user.GetCurrentUser(dc, "ABCD");
    }
    

    static 关键字表示该方法是静态,并且可用于整个类型,而不是绑定到特定实例。这就是为什么当它被标记为静态时,您可以使用类名(并且必须以这种方式调用它)来调用它。

    【讨论】:

    • 补充一点 - static 方法只能访问类中的其他 static 事物,因为它们不绑定到特定实例。
    • 我昨天让自己偏头痛试图解决这个问题。我正在创建函数返回类型的实例,而不是包含该函数的类。如果我现在理解正确的话,如果不创建包含方法定义的类的实例,就不能使用实例方法。
    猜你喜欢
    • 1970-01-01
    • 2016-09-19
    • 1970-01-01
    • 2019-01-28
    • 1970-01-01
    • 2021-03-26
    • 2018-02-19
    • 1970-01-01
    • 2022-01-20
    相关资源
    最近更新 更多