[英]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.