gpt4 book ai didi

c# - 私有(private)静态依赖与私有(private)依赖

转载 作者:行者123 更新时间:2023-11-30 17:01:07 26 4
gpt4 key购买 nike

  public interface ISomeDependency
{
void Calculate( Person person );
}
public class SomeDependency : ISomeDependency
{
void ISomeDependency.Calculate( Person person )
{
person.Age = 30;
}
}

public class Person
{
private static ISomeDependency _someDependency;
public DateTime BirthDate { get; set; }
public int Age { get; set; }
public Person( ISomeDependency someDependency )
{
_someDependency = someDependency;
}
public void CalculateAge()
{
_someDependency.Calculate( this );
}
}
public class Client
{
public Client()
{
Person p = new Person( new SomeDependency() );
p.BirthDate = DateTime.Now.AddYears( -30 );
p.CalculateAge();
}
}

为什么依赖项是否是静态的很重要?一般来说,这重要吗?

最佳答案

Why would it matter if the dependency is static or not? In general, does it matter?

是的 - 在您的情况下,您有一个重置静态成员的实例构造函数,因此静态成员的值将是最后一个构造函数被赋予的值

因为没有理由将我可以看到的依赖项设置为静态(您没有使用它的静态方法/属性)它应该是一个实例(非静态)字段。

关于c# - 私有(private)静态依赖与私有(private)依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21437914/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com