本文整理汇总了C#中Dictionary.TryGetValue方法的典型用法代码示例。如果您正苦于以下问题:C# Dictionary.TryGetValue方法的具体用法?C# Dictionary.TryGetValue怎么用?C# Dictionary.TryGetValue使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Dictionary
的用法示例。
在下文中一共展示了Dictionary.TryGetValue方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: BuildFlowGraph
private static Dictionary<uint, Dictionary<uint, FlowEdge>> BuildFlowGraph(Graph graph)
{
Dictionary<uint, Dictionary<uint, FlowEdge>> flowGraph = new Dictionary<uint, Dictionary<uint, FlowEdge>>();
Dictionary<uint, FlowEdge> dict;
foreach (Vertex v in graph.Vertices.Values)
foreach (Edge e in v.Neighbours.Values)
{
if (!flowGraph.TryGetValue(e.From, out dict))
{
dict = new Dictionary<uint, FlowEdge>();
flowGraph.Add(e.From, dict);
}
dict.Add(e.To, new FlowEdge(e.From, e.To, e.Capacity, e));
if (!flowGraph.TryGetValue(e.To, out dict))
{
dict = new Dictionary<uint, FlowEdge>();
flowGraph.Add(e.To, dict);
}
dict.Add(e.From, new FlowEdge(e.To, e.From, e.Capacity, e));
}
return flowGraph;
}
示例2: MapContentType
static void MapContentType(Dictionary<string, string> headers)
{
string contentType;
if (!headers.TryGetValue("rebus-content-type", out contentType)) return;
if (contentType == "text/json")
{
string contentEncoding;
if (headers.TryGetValue("rebus-encoding", out contentEncoding))
{
headers.Remove("rebus-content-type");
headers.Remove("rebus-encoding");
headers[Headers.ContentType] = $"{JsonSerializer.JsonContentType};charset={contentEncoding}";
}
else
{
throw new FormatException(
"Content type was 'text/json', but the 'rebus-encoding' header was not present!");
}
}
else
{
throw new FormatException(
$"Sorry, but the '{contentType}' content type is currently not supported by the legacy header mapper");
}
}
示例3: onRecieveResult
//override
public void onRecieveResult(Dictionary<String, Object> bundle)
{
Object senderName;
Object senderValue;
bundle.TryGetValue( PageDataExchange.KEY_SENDER_NAME, out senderName);
bundle.TryGetValue(PageDataExchange.KEY_SENDER_VALUE, out senderValue);
string action = senderValue.ToString();
if (PageLogin.LOGIN.Equals(action) || PageLogin.LOGOUT.Equals(action))
{
String title = String.Empty;
String info = String.Empty;
Dictionary<String, Object> pagedata = new Dictionary<string, object>();
PageDataExchange context = PageDataExchange.getInstance();
if (PageLogin.LOGIN.Equals(action))
{
bundle.Add(PageUserRegister.USER_PAGE, PageUserRegister.ID_LOGIN);
context.putExtra(PageUserRegister.TAG, bundle);
Utils.NavigateToPage(MainWindow.sFrameReportName, PageUserRegister.TAG);
}
else if (PageLogin.LOGOUT.Equals(action))
{
bundle.Add(PageUserActionResult.TITLE, "用户登出");
bundle.Add(PageUserActionResult.INFO, "用户" + User.GetInstance().GetCurrentUserInfo().Account + "已登出!");
context.putExtra(PageUserActionResult.TAG, bundle);
Utils.NavigateToPage(MainWindow.sFrameReportName, PageUserActionResult.TAG,false);
}
}
}
示例4: Execute
public StringBuilder Execute(Dictionary<string, StringBuilder> values, IWorkspace theWorkspace)
{
IExplorerRepositoryResult item;
var serializer = new Dev2JsonSerializer();
try
{
if (values == null)
{
throw new ArgumentNullException("values");
}
StringBuilder itemToBeRenamed;
StringBuilder newPath;
if (!values.TryGetValue("itemToMove", out itemToBeRenamed))
{
throw new ArgumentException("itemToMove value not supplied.");
}
if (!values.TryGetValue("newPath", out newPath))
{
throw new ArgumentException("newName value not supplied.");
}
var itemToMove = serializer.Deserialize<ServerExplorerItem>(itemToBeRenamed);
Dev2Logger.Log.Info(String.Format("Move Item. Path:{0} NewPath:{1}", itemToBeRenamed, newPath));
item = ServerExplorerRepo.MoveItem(itemToMove, newPath.ToString(), GlobalConstants.ServerWorkspaceID);
}
catch (Exception e)
{
Dev2Logger.Log.Error(e);
item = new ExplorerRepositoryResult(ExecStatus.Fail, e.Message);
}
return serializer.SerializeToBuilder(item);
}
示例5: ReplaceCode
public AP.ChangeInfo[] ReplaceCode() {
List<AP.ChangeInfo> edits = new List<AP.ChangeInfo>();
var oldLineMapping = new Dictionary<string, List<int>>(); // line to line #
for (int i = 0; i < _oldLines.Length; i++) {
List<int> lineInfo;
if (!oldLineMapping.TryGetValue(_oldLines[i].Text, out lineInfo)) {
oldLineMapping[_oldLines[i].Text] = lineInfo = new List<int>();
}
lineInfo.Add(i);
}
int curOldLine = 0;
for (int curNewLine = 0; curOldLine < _oldLines.Length && curNewLine < _newLines.Length; curOldLine++) {
if (_oldLines[curOldLine].Text == _newLines[curNewLine].Text) {
curNewLine++;
continue;
}
bool replaced = false;
// replace starts on this line, figure out where it ends...
int startNewLine = curNewLine;
for (curNewLine += 1; curNewLine < _newLines.Length; curNewLine++) {
List<int> lines;
if (oldLineMapping.TryGetValue(_newLines[curNewLine].Text, out lines)) {
foreach (var matchingLineNo in lines) {
if (matchingLineNo > curOldLine) {
// Replace the lines from curOldLine to matchingLineNo-1 with the text
// from startNewLine - curNewLine - 1.
ReplaceLines(edits, curOldLine, matchingLineNo, startNewLine, curNewLine);
replaced = true;
curOldLine = matchingLineNo - 1;
break;
}
}
}
if (replaced) {
break;
}
}
if (!replaced) {
ReplaceLines(edits, curOldLine, _oldLines.Length, startNewLine, _newLines.Length);
curOldLine = _oldLines.Length;
break;
}
}
if (curOldLine < _oldLines.Length) {
// remove the remaining new lines
edits.Add(
AP.ChangeInfo.FromBounds(
"",
_oldLines[curOldLine].Start,
_oldLines[_oldLines.Length - 1].End
)
);
}
return edits.ToArray();
}
示例6: UniformMutation
public UniformMutation(Dictionary<string, object> parameters)
: base(parameters)
{
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
object parameter;
if (parameters.TryGetValue("probability", out parameter))
{
_mutationProbability = (double) parameter;
}
else
{
throw new Exception("mutationProbability_ is a NaN");
}
if (parameters.TryGetValue("perturbation", out parameter))
{
_perturbation = (double) parameter;
}
else
{
throw new Exception("perturbation_ is a NaN");
}
}
示例7: CJFunction
public CJFunction(ITypeDatabaseReader typeDb, string name, Dictionary<string, object> functionTable, IMemberContainer declaringType, bool isMethod = false)
{
_name = name;
object doc;
if (functionTable.TryGetValue("doc", out doc)) {
_doc = doc as string;
}
object value;
if (functionTable.TryGetValue("builtin", out value)) {
_isBuiltin = Convert.ToBoolean(value);
} else {
_isBuiltin = true;
}
if (functionTable.TryGetValue("static", out value)) {
_isStatic = Convert.ToBoolean(value);
} else {
_isStatic = true;
}
_hasLocation = JTypeDatabase.TryGetLocation(functionTable, ref _line, ref _column);
_declaringModule = CJModule.GetDeclaringModuleFromContainer(declaringType);
object overloads;
functionTable.TryGetValue("overloads", out overloads);
_overloads = LoadOverloads(typeDb, overloads, isMethod);
_declaringType = declaringType as IJType;
}
示例8: BuildFLASHImages
public static List<ProgrammableRegion> BuildFLASHImages(string targetPath, Dictionary<string, string> bspDict, Dictionary<string, string> debugMethodConfig, LiveMemoryLineHandler lineHandler)
{
string bspPath = bspDict["SYS:BSP_ROOT"];
string toolchainPath = bspDict["SYS:TOOLCHAIN_ROOT"];
string freq, mode, size;
debugMethodConfig.TryGetValue("com.sysprogs.esp8266.xt-ocd.flash_freq", out freq);
debugMethodConfig.TryGetValue("com.sysprogs.esp8266.xt-ocd.flash_mode", out mode);
debugMethodConfig.TryGetValue("com.sysprogs.esp8266.xt-ocd.flash_size", out size);
string partitionTable, bootloader, txtAppOffset;
bspDict.TryGetValue("com.sysprogs.esp32.partition_table_file", out partitionTable);
bspDict.TryGetValue("com.sysprogs.esp32.bootloader_file", out bootloader);
bspDict.TryGetValue("com.sysprogs.esp32.app_offset", out txtAppOffset);
uint appOffset;
if (txtAppOffset == null)
appOffset = 0;
else if (txtAppOffset.StartsWith("0x"))
uint.TryParse(txtAppOffset.Substring(2), NumberStyles.HexNumber, null, out appOffset);
else
uint.TryParse(txtAppOffset, out appOffset);
if (appOffset == 0)
throw new Exception("Application FLASH offset not defined. Please check your settings.");
partitionTable = VariableHelper.ExpandVariables(partitionTable, bspDict, debugMethodConfig);
bootloader = VariableHelper.ExpandVariables(bootloader, bspDict, debugMethodConfig);
if (!string.IsNullOrEmpty(partitionTable) && !Path.IsPathRooted(partitionTable))
partitionTable = Path.Combine(bspDict["SYS:PROJECT_DIR"], partitionTable);
if (!string.IsNullOrEmpty(bootloader) && !Path.IsPathRooted(bootloader))
bootloader = Path.Combine(bspDict["SYS:PROJECT_DIR"], bootloader);
if (string.IsNullOrEmpty(partitionTable) || !File.Exists(partitionTable))
throw new Exception("Unspecified or missing partition table file: " + partitionTable);
if (string.IsNullOrEmpty(bootloader) || !File.Exists(bootloader))
throw new Exception("Unspecified or missing bootloader file: " + bootloader);
List<ProgrammableRegion> regions = new List<ProgrammableRegion>();
using (var elfFile = new ELFFile(targetPath))
{
string pathBase = Path.Combine(Path.GetDirectoryName(targetPath), Path.GetFileName(targetPath));
var img = ESP8266BinaryImage.MakeESP32ImageFromELFFile(elfFile, new ESP8266BinaryImage.ParsedHeader(freq, mode, size));
//Bootloader/partition table offsets are hardcoded in ESP-IDF
regions.Add(new ProgrammableRegion { FileName = bootloader, Offset = 0x1000, Size = GetFileSize(bootloader) });
regions.Add(new ProgrammableRegion { FileName = partitionTable, Offset = 0x8000, Size = GetFileSize(partitionTable) });
string fn = pathBase + "-esp32.bin";
using (var fs = new FileStream(fn, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
{
img.Save(fs);
regions.Add(new ProgrammableRegion { FileName = fn, Offset = (int)appOffset, Size = (int)fs.Length });
}
}
return regions;
}
示例9: onRecieveResult
//public void registerObserver(IObserverResult observer)
//{
// mObserver = observer;
//}
//private void notifyChanged(Dictionary<String, Object> bundle)
//{
// if (mObserver != null)
// {
// mObserver.onRecieveResult(bundle);
// }
//}
public void onRecieveResult(Dictionary<String, Object> bundle)
{
//mBundle = bundle;
Object senderName;
Object senderValue;
Object senderLimit;
bundle.TryGetValue(PageDataExchange.KEY_SENDER_NAME, out senderName);
bundle.TryGetValue(PageDataExchange.KEY_SENDER_VALUE, out senderValue);
bundle.TryGetValue(PageDataExchange.KEY_THREAD_HOLD, out senderLimit);
float max = 100;
float min = 0;
BeckHoff.ThresHold limit = (BeckHoff.ThresHold)senderLimit;
if (limit != null)
{
max = (float)limit.max / limit.ratio;
min = (float)limit.min / limit.ratio;
}
this.tb_limit_max.Text = max.ToString();
this.tb_limit_min.Text = min.ToString();
this.tb_current_value.Text = senderValue.ToString();
this.lb_input.Content = "";
mSourceControlName = senderName.ToString();
}
示例10: Build
internal static void Build(Dictionary<MonikerHelper.MonikerAttribute, string> propertyTable, ref Guid riid, IntPtr ppv)
{
if (IntPtr.Zero == ppv)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("ppv");
Marshal.WriteIntPtr(ppv, IntPtr.Zero);
string temp;
IProxyCreator proxyCreator = null;
if (propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.Wsdl, out temp))
{
proxyCreator = new WsdlServiceChannelBuilder(propertyTable);
}
else if (propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.MexAddress, out temp))
{
proxyCreator = new MexServiceChannelBuilder(propertyTable);
}
else
{
proxyCreator = new TypedServiceChannelBuilder(propertyTable);
}
IProxyManager proxyManager = new ProxyManager(proxyCreator);
Marshal.WriteIntPtr(ppv, OuterProxyWrapper.CreateOuterProxyInstance(proxyManager, ref riid));
}
示例11: Delaunay_Voronoi
/// <summary>
/// Initializes a new instance of the class Delaunay_Voronoi_Library.Delaunay_Voronoi with the specified initial Delaunay_Voronoi class.
/// </summary>
/// <param name="delaunay_voronoi">The Delaunay_Voronoi class.</param>
public Delaunay_Voronoi(Delaunay_Voronoi delaunay_voronoi)
{
Dictionary<Vertex, Vertex> dictionary_parallel_copy = new Dictionary<Vertex, Vertex>();
foreach (var w in delaunay_voronoi.GetVertices)
{
Vertex parallel_copy = new Vertex(w);
dictionary_parallel_copy.Add(w, parallel_copy);
this.GetVertices.Add(parallel_copy);
}
foreach (var w in delaunay_voronoi.triangles)
{
Vertex vertex1, vertex2, vertex3;
dictionary_parallel_copy.TryGetValue(w.GetVertices[0], out vertex1);
dictionary_parallel_copy.TryGetValue(w.GetVertices[1], out vertex2);
dictionary_parallel_copy.TryGetValue(w.GetVertices[2], out vertex3);
this.triangles.Add(new triangle(vertex1,vertex2,vertex3));
}
foreach (var w in delaunay_voronoi.pol)
{
Vertex vertex;
dictionary_parallel_copy.TryGetValue(w.GetCellCentr, out vertex);
VoronoiCell newvc = new VoronoiCell(w,vertex);
vertex.Voronoi_Cell = newvc;
pol.Add(newvc);
}
}
示例12: DictionaryBasics
public void DictionaryBasics()
{
var map = new Dictionary<string, int>();
map.Add("foo", 10);
map["bar"] = 20;
//foreach (var entry in map)
//{
// Console.WriteLine("{0}: {1}", entry.Key, entry.Value);
//}
int value;
bool keyFound = map.TryGetValue("blah", out value);
Assert.IsFalse(keyFound);
Assert.AreEqual(0, value);
keyFound = map.TryGetValue("foo", out value);
Assert.IsTrue(keyFound);
Assert.AreEqual(10, value);
Assert.AreEqual(2, map.Count);
map = new Dictionary<string, int>
{
{"xyz", 3},
{"abc", 4}
};
// map.Add("xyz", 3); //ERROR -> Already added
}
示例13: SongInfo
public SongInfo(Dictionary<string, string> data)
{
this._title = null;
if (data.ContainsKey ("Title"))
this._title = data ["Title"];
else if (data.ContainsKey ("Name"))
this._title = data ["Name"];
data.TryGetValue ("Album", out this._album);
data.TryGetValue ("Artist", out this._artist);
if ((this._title == null) && (data.ContainsKey("file")))
{
var segments = data["file"].Split(Path.DirectorySeparatorChar);
if (segments.Length > 0)
{
this._title = Path.GetFileNameWithoutExtension(segments [segments.Length - 1]
//.TrimStart('0', '1', '2', '3', '4', '5', '6', '7', '8', '9')
.Trim());
}
if ((segments.Length > 1) && (this._album == null))
this._album = segments [segments.Length - 2];
if ((segments.Length > 1) && (this._artist == null))
this._artist = segments [segments.Length - 3];
}
}
示例14: onRecieveResult
//override IObserverResult
public void onRecieveResult(Dictionary<String, Object> bundle)
{
Object senderName;
Object senderValue;
bundle.TryGetValue( PageDataExchange.KEY_SENDER_NAME, out senderName);
bundle.TryGetValue(PageDataExchange.KEY_SENDER_VALUE, out senderValue);
String action = senderValue.ToString();
if (PageLogin.LOGIN.Equals(action))
{
this.tb_login.Text = "注销";
}
else if (PageLogin.LOGOUT.Equals(action))
{
this.tb_login.Text = "登陆";
}
else if (PageLogin.KILLKEYBOARD.Equals(action))
{
this.btn_keyboard.Visibility = Visibility.Hidden;
exitKeyboard();
return;
}
else if (PageLogin.SHOWKEYBOARD.Equals(action))
{
this.btn_keyboard.Visibility = Visibility.Visible ;
return;
}
LoginState();
}
示例15: TryGetValueFixture
public void TryGetValueFixture()
{
var dict = new Dictionary<string, int>() { { "a",1 }, { "b",2 } };
dict.TryGetValue("b").Should().Equal(2);
dict.TryGetValue("c").Should().Be.Null();
(dict.TryGetValue("c") ?? 3).Should().Equal(3);
}