简体   繁体   English

C#后期绑定

[英]C# Late Binding

I have a "simple" problem, and I crated an example app to illustrate. 我有一个“简单”的问题,我创建了一个示例应用程序进行说明。 I would like the b.getName() call to return "barname", but it does not, and I'm not sure how to get this to work. 我希望b.getName()调用返回“ barname”,但它不会,并且我不确定如何使它工作。 I've been working in C# for years, but at the moment I feel like a newbie because this late binding problem has me stumped. 我已经在C#中工作了很多年,但是现在我觉得自己像个新手,因为这个后期的绑定问题让我很头疼。

class Program
{
    static void Main(string[] args)
    {
        bar b = new bar();
        Console.WriteLine(b.getName());
        Console.ReadLine();
    }
}

class foo
{
    string name = "fooname";

    public string getName()
    {
        return this.name;
    }
}

class bar:foo
{
    string name = "barname";
}

By default your name variable is private - it sounds like you want it to be protected , so you can overwrite the value - this would work: 默认情况下,您的name变量是private-听起来像您希望对其进行protected ,因此您可以覆盖该值-这可以工作:

class foo
{
    protected string name = "fooname";

    public string getName()
    {
        return this.name;
    }
}

class bar : foo
{
    public bar()
    {
        name = "barname";
    }
}

If you're not married to having a private class variable, you can accomplish this with an overridden property: 如果您不愿意拥有一个私有类变量,则可以使用覆盖的属性来实现:

class foo
{
    public virtual string Name
    {
        get
        {
            return "fooname";
        }
    }
}

class bar : foo
{
    public override string Name
    {
        get
        {
            return "barname";
        }
    }
}

This isn't related to late binding. 这与后期绑定无关。 Late binding generally refers to calling a method at runtime from the name. 后期绑定通常是指在运行时从名称中调用方法。

What your supplied code actually does is create a new variable that's in a different scope than what your base class has access to. 您提供的代码实际上所做的是创建一个新变量,该新变量的作用域与您的基类无法访问的变量相同。

In order to get the desired effect, you actually need to either 1) make the base class method implementation virtual, and override the method in your child, or 2) in your base class change your variable to have a default accessibility of protected and set the value in your derived class's constructor(s). 为了获得理想的效果,您实际上需要1)使基类方法实现虚拟化,并在您的孩子中重写该方法,或者2)在基类中更改变量以使其具有默认的可访问性protected和set派生类的构造函数中的值。

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

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