试试这个实现地图的类(正如马里奥建议的那样)。
将idValueDictionary
映射id
到refValue
,将valueNameDictionary
映射refValue
到nameValue
。字典是硬编码的,但如果它适合您的需要,您可以在运行时加载数据。
using System;
using System.Collections.Generic;
class ContentDetails
{
// Maps id to RefValue.
private static readonly Dictionary<string, string> idValueDictionary =
new Dictionary<string,string>()
{
{ "00", "14" },
{ "01", "18" },
{ "XX", "00" }
};
// Maps RefValue to ViewName
private static readonly Dictionary<string, string> valueNameDictionary =
new Dictionary<string,string>()
{
{ "00", "Menu" },
{ "14", "Menu" },
{ "18", "Topic" }
};
// Private constructor. Use GetContentDetails factory method.
private ContentDetails(string refValue, string viewName)
{
this.RefValue = refValue;
this.ViewName = viewName;
}
// Gets the RefValue.
public string RefValue
{
get;
private set;
}
// Gets the ViewName.
public string ViewName
{
get;
private set;
}
// Creates a new ContentDetails from the specified id.
public static ContentDetails GetContentDetails(string id)
{
// Extract key from id.
string key = id.Substring(2,2);
// If key not in dictionary, use the default key "XX".
if (!idValueDictionary.ContainsKey(key))
{
key = "XX";
}
// Get refValue and viewName from dictionaries.
string refValue = idValueDictionary[key];
string viewName = valueNameDictionary[refValue];
// Return a new ContentDetails object with properties initialized.
return new ContentDetails(refValue, viewName);
}
}
像这样使用它:
// Static factory method creates a new ContentDetails from the specified `id`
ContentDetails details = ContentDetails.GetContentDetails(id);
Console.WriteLine(details.RefValue); // writes RefValue
Console.WriteLine(details.ViewName); // writes ViewName
ContentDetails
使用该方法创建一个新GetContentDetails
属性后,您可以访问这两个属性以获取RefValue
和ViewName
。这些属性是只读的 ( private set
),因此一旦创建了类实例(它是不可变的),您就无法更改值。每次你有不同id
的查找时创建一个新的。