当前位置: 动力学知识库 > 问答 > 编程问答 >

What is the C# equavilent of C++ :: (non-static)

问题描述:

I've been working with C++ for a while now, and I picked up C# a few weeks ago. When writing initialisers, I have found that I do not know a way to use the :: operator.

In C++, it looks like:

class something{

bool a;

void doSg();

}

void doSg(){

something::a = true;

}

int main()

{

something mySg;

mySg.doSg();

}

So, I tried to recreate the void doSg() function in C#: a method that modifies that class object's data that it's been called for.

In the following code:

class something

{

bool a;

public void func()

{

this.a = true;

}

}

class source

{

something mySg;

mySg.func();

}

is this.a = true valid, or should I make:

class something

{

bool a;

public myclass func(myclass item)

{

item.a = true;

return item;

}

}

class source

{

something mySg;

mySg = func(mySg);

}

Or is there a better solution?

网友答案:

var here is a keyword so it probably would not work like you are using it. You can do something like this:

class something {
    bool myBool; 

    public void func()
    {
        this.myBool= true;
        myBool= true;  //or you can just leave this "this" off
    } 
}

When calling something.func() it will set myBool to true.

"this" just refers to the class(or struct) itself and does not need to be used that often. You just need it in the event that there are duplicate names like this...

class something {
    bool myBool; 

    public void func(bool myBool)
    {
        myBool= myBool; //would not do anything
        this.myBool= myBool;  //force class myBool
    } 
}

As for return, you would need it for that second example you have listed but the var needs to be changed or removed.

class something
{
public Myclass func(myclass item)
    {
        Myclass item = new myClass(); // first create a class
        return item; //since myclass in in the header, we need to return a myclass
    }
}

I updated the myClass to MyClass because classes should start with a captial but this is not required. I hope this helps some. C# is different then C++ when it comes to all the details.

分享给朋友:
您可能感兴趣的文章:
随机阅读: