开发者

Issue with using get keyword in C# relating to inheritance

开发者 https://www.devze.com 2023-04-04 19:21 出处:网络
So I am having some issues with this. I am kinda new to C#. All my attributes are private and I am using the tradi开发者_JS百科tional get and set. It is an abstract class. But in the child class when

So I am having some issues with this. I am kinda new to C#. All my attributes are private and I am using the tradi开发者_JS百科tional get and set. It is an abstract class. But in the child class when I try and use it in another method, the compiler says cannot use as a method. However if I do the C++ way of accesors and mutators it works fine. Is there a way around this?

Thanks very much for your help

Never mind I got it. I have just been coding for like 7 hrs straight to get this assignment done for school and my brain isn't working right lol thanks very much though


This would be the standard C# way of doing what (I think) you're asking.

public abstract class Base
{
    // Automatic Property
    public string Prop1 { get; set; }

    // With backing field
    private string prop2;
    public string Prop2
    {
        get { return prop2; }
        set { prop2 = value; }
    }
}

public class Derived : Base
{
    public string Prop3 { get; set; }
}

public class AnotherClass
{
    void Foo()
    {
        var derived = new Derived();
        // Can get and set all properties
        derived.Prop1 = derived.Prop1;
        derived.Prop2 = derived.Prop2;
        derived.Prop3 = derived.Prop3;
    }
}
0

精彩评论

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

关注公众号