【问题标题】:C# functions in common class not recognized in code-behind公共类中的 C# 函数在代码隐藏中无法识别
【发布时间】:2011-10-14 15:49:05
【问题描述】:

使用 vwd express 2010 将 vb web 项目转换为 c#。 开发系统是64位windows 7。

我有一个在外部 cs 文件中声明的常用函数。 文件“clsCommon.cs”的内容=

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net.Mail;

namespace Project_Website
{
    public class clsCommon
    {
        public void testA()
        {

        }

    } // clsCommon
} // namespace

在后面的代码中,我尝试访问函数 testA(),如下所示:

testA();

也试过了:

clsCommon.testA();

Project_Website.clsCommon.testA();

我想使用的实际示例更复杂,但这是最简单的示例,它体现了我在下面列举的问题:

  1. 当我键入时,Intellisense 识别 clsCommon,但不认为 testA() 是其中的方法。 Intellisense 只看到两种方法:Equals() 和 ReferenceEquals()。

  2. 我忽略 Intellisense 并编译,这会产生以下错误消息:

错误 1 ​​非静态字段、方法或属性“Project_Website.clsCommon.testA()”需要对象引用

这个问题的根本原因是什么?

【问题讨论】:

    标签: c# class function global vwdexpress


    【解决方案1】:

    您要么需要创建该方法static,要么创建类clsCommon 的实例来使用它,即:

    public class clsCommon
    {
        public static void testA()
        {
    
        }
    
    } // clsCommon
    

    请注意,上面的方法签名会产生“副作用”,因为您没有返回任何内容,也没有传递任何内容。如果您正在修改该类的其他成员或属性,您应该创建一个实例并使用成员方法:

    var common = new clsCommon();
    common.testA();
    

    如果您不需要使用clsCommon 类访问任何其他属性或方法,您应该只创建方法static。如果您的所有方法都是这种情况,并且clsCommon 只是持有一堆实用方法,那么您也应该将clsCommon 类设为静态。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-22
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多