【问题标题】:c# implemented interface variable used in derived classc#实现派生类中使用的接口变量
【发布时间】:2019-04-16 14:49:45
【问题描述】:

我正在尝试在 A 类中实现一个接口方法,通过该实现我想从输入中给出变量 g 值,然后能够在其他派生类中读取该 g 值。问题是,没有派生类能够看到该值。似乎是什么问题?

interface ISomething
{
    void something(string some);
}
public class A : ISomething
{
    public string g;
    public void something(string some)
    {
        g = some;
    }
}
public class B : A
{
    public void methodB()
    {
        Console.WriteLine($"Printing g value from method B: {g}");
    }

}
public class C : A
{
    public void methodC()
    {
        Console.WriteLine($"Printing g value from method C: {g}");
    }
}
public class D : B
{
    public void methodD()
    {
        Console.WriteLine($"Printing g value from method D: {g}");
    }
}

static void Main(string[] args)
    {
        Console.WriteLine("Input something: ");
        string x = Console.ReadLine();
        A a = new A();
        a.something(x);
        B b = new B();
        C c = new C();
        D d = new D();
        b.methodB();
        c.methodC();
        d.methodD();
        Console.ReadKey();
    }

【问题讨论】:

    标签: class variables interface implementation derived


    【解决方案1】:

    仅仅因为BCD 继承自A 并不意味着它们的field g 将被初始化为任何东西。创建的每个对象仍然是一个独立的对象,仅仅因为您声明了一个类型为 A 的对象并不意味着从 A 继承的每个类实例都将保存与您创建的 A 实例相同的字段值。您应该通过调用something() 方法来设置每个派生类的field g,因此将您的代码更改为:

    B b = new B();
    C c = new C();
    D d = new D();
    d.something(x);
    c.something(x);
    b.something(x);
    b.methodB();
    c.methodC();
    d.methodD();
    

    【讨论】:

      猜你喜欢
      • 2010-09-22
      • 2017-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-22
      • 2014-06-17
      相关资源
      最近更新 更多