我知道我不应该问这个问题,但不管是什么,我都错过了让我疯了!我以前做了很多次,我只能把它放到老年和轻微的衰老.
我有一个类,有两个对象,在构造函数中初始化...
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
}
}
Run Code Online (Sandbox Code Playgroud)
然后我有一个表单应用程序(测试工具),使用该类和按钮单击我调用方法...
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");
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是,apiContext在调用之间storeCategories会持续存在但会被填充,EbayFunctions ebf = new EbayFunctions();并且在调用时string ddd = ebf.GetStoreCategoryIdForItem("Motors > Bikes");为null .
我知道它有些愚蠢,但我错过了什么?
你的问题在这里:
private static ApiContext apiContext = null;
private static List<StoreCategoriesFlattened> storeCategories = new List<StoreCategoriesFlattened>();
public EbayFunctions()
{
ApiContext apiContext = GetApiContext(); // local!!
List<StoreCategoriesFlattened> storeCategories = GetFlattenedStoreCategories(); // local!!
}
Run Code Online (Sandbox Code Playgroud)
你没有设置静态字段 - 你引入的局部变量然后超出范围并且(最终)被垃圾收集.取出类型指标来设置静态字段:
public EbayFunctions()
{
apiContext = GetApiContext();
storeCategories = GetFlattenedStoreCategories();
}
Run Code Online (Sandbox Code Playgroud)
另外,正如@PatrickHofman指出的那样,静态成员的初始化应该进行一次 - 最好是在静态构造函数中:
static EbayFunctions()
{
apiContext = GetApiContext();
storeCategories = GetFlattenedStoreCategories();
}
Run Code Online (Sandbox Code Playgroud)