gpt4 book ai didi

C# : make derived object conditionally share same base object

转载 作者:行者123 更新时间:2023-11-30 20:18:59 24 4
gpt4 key购买 nike

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

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");
}

最佳答案

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

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];
}
}

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

关于C# : make derived object conditionally share same base object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39751720/

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