简体   繁体   English

使用通用基类在对象上调用受保护的方法

[英]Calling a protected method on a object with a common base class

I need to be able to access a protected property/method on an object with the common base class to the calling scope. 我需要能够使用调用范围的公共基类访问对象上的受保护属性/方法。 The compiler doesn't seem to like this at all. 编译器似乎根本不喜欢这样。

class Base
{
    protected int Data { get; set; }
}
class SubClasss1 : Base
{

}
class SubClasss2 :Base
{
    public SubClasss1 MyFunction() {
        SubClasss1 x = new SubClasss1();
        x.Data = this.Data; // NOT HAPPY
        return x;
    }
}

I've figured this may work, but it doesn't 我认为这可能有效,但没有效果

((Base)copy).Data = ...

This does work but is a bit ugly 这确实有效,但有点难看

class Base
{
    protected int Data { get; set; }
    protected int GetData(Base obj) { return obj.Data; }
    protected void SetData(Base obj, int value) { obj.Data = value; }
}

class SubClasss1 : Base
{

}

class SubClasss2 : Base
{
    public SubClasss1 MyFunction()
    {
        SubClasss1 x = new SubClasss1();
        this.SetData(x, this.Data);
        return x;
    }
}

I was trying to avoid using protected internal as I don't want to clutter the public interface within the project. 我试图避免使用受保护的内部,因为我不想弄乱项目中的公共接口。

This is because protected member can be accessed with in the derived class not outside of it. 这是因为可以在派生类中访问受保护的成员,而不是在其外部进行访问。 What you can do is add it to constructor like: 您可以做的是将其添加到构造函数中,例如:

class SubClasss1 : Base
{
    public SubClasss1(int data)
    {
        Data = data; // can be accessed within the class but not from outside
    }
}

and then you would need to provide it: 然后您需要提供:

class SubClasss2 : Base
{
    public SubClasss1 MyFunction()
    {
        SubClasss1 copy = new SubClasss1(this.Data);

        return copy;
    }
}

One way can be create public set method in SubClasss2 and then you should be able to read the value of it and set it into SubClass1 in your Myfucntion . 一种方法是在SubClasss2创建公共设置方法,然后您应该能够读取它的值并将其设置为Myfucntion SubClass1

class Base
{
    protected int Data { get; set; }
    protected int GetData(Base obj) { return obj.Data; }
    protected void SetData(Base obj, int value) { obj.Data = value; }
}

class SubClasss1 : Base
{
    public void SetData(Base obj, int value) { this.Data = value; }
}

class SubClasss2 : Base
{
    public void SetData(Base obj, int value) { this.Data = value; }
    public SubClasss1 MyFunction()
    {
        SubClasss1 x = new SubClasss1();
        x.SetData(x, this.Data);
        return x;
    }
}

class Program
{
    static void Main(string[] args)
    {
        SubClasss2 subClass2Obj= new SubClasss2();
        subClass2Obj.SetData(subClass2Obj, 30);
        var subClass1Obj = subClass2Obj.MyFunction();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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