开发者

C# functions in common class not recognized in code-behind

Converting vb web project to c# using vwd express 2010. Development system is a 64bit windows 7.

I have a commonly used function declared in an external cs file. Contents of file "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

In code behind I try to access the function testA() as follows:

testA();

Also tried:

c开发者_运维技巧lsCommon.testA();

and

Project_Website.clsCommon.testA();

The actual example I want to use is more complicated, but this is the simplest example that manifests the problem(s) I enumerate below:

  1. The As I type, Intellisense recognizes clsCommon, but doesn't think testA() is a method in it. Intellisense only sees two methods: Equals() and ReferenceEquals().

  2. I ignore Intellisense and compile anyway, which produces the following error message:

Error 1 An object reference is required for the non-static field, method, or property 'Project_Website.clsCommon.testA()'

What is the root cause of this problem?


You either need to make that method static, or create an instance of the class clsCommon to use it, i.e.:

public class clsCommon
{
    public static void testA()
    {

    }

} // clsCommon

Note that above method signature screams "side effects" since you don't return anything and are not passing anything in. If you are modifying other members or properties of the class, you should create an instance instead and use a member method:

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

You should only make the method static if you do not need access to any other properties or methods with the clsCommon class. If that is the case for all of your methods, and clsCommon is just holding a bunch of utility methods, you should make the clsCommon class static as well.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜