[英]Object persistence in class between projects
我知道我不必问这个,但是我所缺少的一切都让我发疯! 我以前做过很多次,只能说到年老和衰老。
我有一个带有两个在构造函数中初始化的对象的类...
public class EbayFunctions
{
private static ApiContext apiContext = null;
private static List<StoreCategoriesFlattened> storeCategories = new List<StoreCategoriesFlattened>();
public EbayFunctions()
{
ApiContext apiContext = GetApiContext();
List<StoreCategoriesFlattened> storeCategories = GetFlattenedStoreCategories();
}
public string GetStoreCategoryIdForItem(string category)
{
var result = storeCategories.Find(x => x.CCDatabaseMatch == category);
return ""; //Ignore will return a value
}
}
然后我有一个利用该类的表单应用程序(测试工具),然后单击按钮,我调用一个方法...
namespace EbayTestHarness
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void cmdGetEbayStoreCatID_Click(object sender, EventArgs e)
{
EbayFunctions ebf = new EbayFunctions();
string ddd = ebf.GetStoreCategoryIdForItem("Motors > Bikes");
}
}
}
但是apiContext
在apiContext
调用之间仍然存在,但是storeCategories
在EbayFunctions ebf = new EbayFunctions();
上EbayFunctions ebf = new EbayFunctions();
当string ddd = ebf.GetStoreCategoryIdForItem("Motors > Bikes");
时为null string ddd = ebf.GetStoreCategoryIdForItem("Motors > Bikes");
叫做。
我知道它有些愚蠢,但是我想念的是什么?
您的问题在这里:
private static ApiContext apiContext = null;
private static List<StoreCategoriesFlattened> storeCategories = new List<StoreCategoriesFlattened>();
public EbayFunctions()
{
ApiContext apiContext = GetApiContext(); // local!!
List<StoreCategoriesFlattened> storeCategories = GetFlattenedStoreCategories(); // local!!
}
您不是在设置静态字段,而是在引入局部变量 ,然后这些变量超出范围并(最终)被垃圾回收。 取出类型指示器以设置静态字段:
public EbayFunctions()
{
apiContext = GetApiContext();
storeCategories = GetFlattenedStoreCategories();
}
另外,正如@PatrickHofman指出的那样,静态成员的初始化应该执行一次-最好在静态构造函数中进行:
static EbayFunctions()
{
apiContext = GetApiContext();
storeCategories = GetFlattenedStoreCategories();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.