访问基本classe中的派生类成员

Sai*_*aid 0 c# inheritance

我想访问基本classe中的派生类成员:

class Program
{
    static void Main(string[] args)
    {
        B b = new B();
        b.FieldTest = 5;
        b.MethodeTest();

    }
}

public class A
{
    public void MethodeTest()
    {
        //will return B
        Type t = this.GetType();
        Console.WriteLine(t);

        var temp = ???.FieldTest;
        //i want that these return 5
        Console.WriteLine(temp);
        Console.ReadLine();
    }
}

public class B:A
{
    public int FieldTest;
}
Run Code Online (Sandbox Code Playgroud)

我不确定这些是可能的,但我希望你有任何想法来解决它.

谢谢

Jon*_*eet 6

可以用动态类型做到这一点:

dynamic dynamicThis = this;
var temp = dynamicThis.FieldTest;
Run Code Online (Sandbox Code Playgroud)

......但这是一个非常奇怪的要求.如果this实际上只是一个实例A,或者实际上是没有这样一个成员的不同子类的实例,你会发生什么?基本上它是一个狡猾的设计.

目前尚不清楚您要实现的目标,但您可能希望使用所有子类都可以实现的抽象属性来创建A一个抽象类.(注意你不能把字段抽象......)

如果这没有帮助,请首先详细说明您尝试这样做的原因.