c#:使派生对象有条件地共享同一个基对象

本文关键字:对象 共享 同一个 有条件 派生 | 更新日期: 2023-09-27 18:09:11

我有一个由多个派生类继承的基类。我在构造函数中初始化基类的一些属性。是否有任何方法我可以使基类属性由我的派生对象共享,而不是为每个派生类对象创建相同的属性值。这一点非常重要,因为一些基类属性值是由服务生成的,共享这些属性值可以提高性能。下面是我想说的一个简单的蓝图:

public class ClassA
{
    //i dont want to use static here as it will be shared for multiple codes
    protected string country { get; set; }
    public ClassA(string code)
    {
        country = CallsomeService(code);
    }
}
public class ClassB : ClassA
{
    public ClassB(string code) : base(code)
    {
        //blah blah
    }
    public void DomeSomethingWithCountry()
    {
        Console.WriteLine($"doing this with {country} in classB");
    }
}
public class ClassC : ClassA
{
    public ClassC(string code) : base(code)
    {
        //blah blah
    }
    public void DomeSomethingWithCountry()
    {
        Console.WriteLine($"doing soemthing else with {country} in classC");
    }
}

现在制作下面的对象

     public void test()
        {
            //call service for this
            var classb=new ClassB("1");
            //dont call service for this
            var classc=new ClassC("1");
classb.DomeSomethingWithCountry();
classc.DomeSomethingWithCountry();
            //call service for this as code is different
            var classb1=new ClassB("2");
        }

c#:使派生对象有条件地共享同一个基对象

可以静态存储调用后的结果,而不是值本身。

public class ClassA
{
    static Dictionary<string,string> codeToCountryLookup
         = new Dictionary<string,string>();
    protected string country { get; set; }
    public ClassA(string code)
    {
       if(!codeToCountryLookup.ContainsKey(code))
            codeToCountryLookup.Add(code,CallsomeService(code));
       country = codeToCountryLookup[code];
    }
}

这不是线程安全的,但应该给你一个开始的地方。