简体   繁体   中英

C# how to get current class instance equivalent to self php

Lets suppose we have these classes:

class A {
    public string attr = "Class A";

    public static void getAttribute(){
         self currentClass = new self(); // equivalent to php
         Console.Write("Attribute : " + currentClass.attr);
    }
}

Class B : A {
    public string attr = "Class B";
}

B = new B();
B.getAttribute();

I want B.getAttribute(); to print Attribute: Class B . How can I do this?

This is fundamentally impossible.

B.getAttribute() compiles to A.getAttribute() .

I probably know what you are trying to do, but I have to tell you that this kind of PHP approach makes no sense in C#. I discourage you from using it.

public class A
{
    private String attr = "Class A";

    public static String getAttribute()
    {
        return (new A()).attr;
    }
}

public class B : A
{
    private String attr = "Class B";

    public static String getAttribute()
    {
        return (new B()).attr;
    }
}

If you're asking how to do something like that in C#, I think the answer would be along these lines:

public class A
{
    public virtual string attr 
    {       
        get { return "Class A" }
    }

    public void getAttribute(){
         Console.Write("Attribute : " + attr);
    }
}

public class B : A
{
    public override string attr 
    {       
        get { return "Class B"; }
    }
}

var b = new B();

b.getAttribute();

Regarding my comment in the other answer, if you needed getAttribute to be static, you could implement it this way:

public static void getAttribute(A obj){
     Console.Write("Attribute : " + obj.attr);
}

You would then call it like this:

var b = new B();
A.getAttribute(b);

You get the current class instance by the 'this' keyword. Obviously you cannot access that in a static method since by definition a static method executes without the context of a particular instance.

On the other hand, to access a member variable/property/method from inside the same class, you don't need the 'this' keyword at all, since it's implicit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM