如何使参考肤浅

艾尔菲斯(Aelphaeis)

我想知道如何迫使一个变量始终指向另一个变量所指向的对象。

考虑以下程序:

using System;

public class Program
{
    public static void Main()
    {
        Person p = new Person{Name = "Aelphaeis", Age = -1};
        p.introBehavior.Introduce();
    }

    class Person
    {
        public String Name { get;set; }
        public Int32 Age { get;set; }

        public IIntroductionBehavior introBehavior{get;set;}

        public Person(){
            Name = "over";
            Age = 9000;

            introBehavior = new IntroductionBehavior(Name, Age);
        }
    }

    class IntroductionBehavior : IIntroductionBehavior
    {
        String Name;
        Int32 Age;

        public IntroductionBehavior(string  name, int age){
            Age = age;
            Name = name;
        }

        public void Introduce(){
            Console.WriteLine("I'm " + Name + " and I am " + Age + " years old");
        }

    }

    interface IIntroductionBehavior
    {
        void Introduce();
    }   
}

如果您运行此程序,您将获得

我结束了,我已经9000岁

所需的行为是,IntroductionBehavior内部的Name和Age指向Person内部的属性值也要指向。它应该打印:

我是Aelphaeis,今年-1岁

如果不可能,那么我将执行哪种类型的重新设计以确保IntroductionBehavior始终在不使IntroductionBehavior意识到Person的情况下打印Person的值?

编辑:很多人似乎对为什么我不想让IntroductionBehavior Aware of Person感到困惑。

引入实际上旨在在存储库上执行操作。变量名称和年龄表示将要操作的存储库。我正在尝试松散耦合,以便易于调试。

谢尔盖·别列佐夫斯基(Sergey Berezovskiy)

给人IntroductionBehavior参考:

class IntroductionBehavior : IIntroductionBehavior
{
    private Person person;

    public IntroductionBehavior(Person person){
        this.person = person;
    }

    public void Introduce(){ 
        Console.WriteLine("I'm {0} and I am {1} years old", 
           person.Name, person.Age); // NOTE: use string format
    }
}

class Person
{
    public String Name { get; set; }
    public Int32 Age { get; set; }

    public IIntroductionBehavior introBehavior { get; set; }

    public Person(){
        Name = "over";
        Age = 9000;
        introBehavior = new IntroductionBehavior(this);
    }
}

这样IntroductionBehavior,当您要求介绍姓名和年龄时,就会得到姓名或年龄值或人称。

另一个选择是IntroductionBehavior在属性getter中创建实例,而不是在构造函数中创建实例:

  public IIntroductionBehavior introBehavior
  {
     get { return new IntroductionBehavior(Name, Age); }
  }

因此,IntroductionBehavior将在您获取人的姓名和年龄值时(而不是在创建人时)捕获该人的姓名和年龄值。注意:如果您在获取introBehavior和介绍人的名字或年龄之前对其进行更新,则会看到旧的数据。

当然,使用IntroductionBehavior类是有争议的。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章