本文整理汇总了C#中IDictionary.TryGetValue方法的典型用法代码示例。如果您正苦于以下问题:C# IDictionary.TryGetValue方法的具体用法?C# IDictionary.TryGetValue怎么用?C# IDictionary.TryGetValue使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类IDictionary
的用法示例。
在下文中一共展示了IDictionary.TryGetValue方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ReplaceResourceUris
public static IGraph ReplaceResourceUris(IGraph original, IDictionary<string, Uri> replacements)
{
IGraph modified = new Graph();
foreach (Triple triple in original.Triples)
{
Uri subjectUri;
if (!replacements.TryGetValue(triple.Subject.ToString(), out subjectUri))
{
subjectUri = ((IUriNode)triple.Subject).Uri;
}
INode subjectNode = modified.CreateUriNode(subjectUri);
INode predicateNode = triple.Predicate.CopyNode(modified);
INode objectNode;
if (triple.Object is IUriNode)
{
Uri objectUri;
if (!replacements.TryGetValue(triple.Object.ToString(), out objectUri))
{
objectUri = ((IUriNode)triple.Object).Uri;
}
objectNode = modified.CreateUriNode(objectUri);
}
else
{
objectNode = triple.Object.CopyNode(modified);
}
modified.Assert(subjectNode, predicateNode, objectNode);
}
return modified;
}
示例2: Load
private void Load(IDictionary<string, int> parameters)
{
var subjectId = 0;
var definitionId = 0;
parameters.TryGetValue ("SubjectId", out subjectId);
parameters.TryGetValue ("DefinitionId", out definitionId);
parameters.TryGetValue ("Mode", out _currentMode);
MeasurementSubjectId = subjectId;
if (definitionId == 0) {
var measurement = _instanceRepository.GetAll (predicate: null, orderBy: (o) => o.DateRecorded, descending: true, skip: 0, count: 1).FirstOrDefault ();
if (measurement != null) {
LoadFromDefinition (measurement.MeasurementDefinitionId, measurement.MeasurementSubjectId);
}
} else {
LoadFromDefinition (definitionId, subjectId);
}
UnregisterMessages ();
}
示例3: CreateProvider
/// <inheritdoc/>
public IConnectionProvider CreateProvider(
IDictionary<string, string> options) {
string connection_string;
if (options.TryGetValue(kConnectionStringOption, out connection_string)) {
return new SqlConnectionProvider(connection_string);
}
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = GetOption(kServerOption, options);
// We try to get the user name information using the "login" key for
// backward compatibility.
string user_id;
if (!options.TryGetValue(kLoginOption, out user_id)) {
user_id = GetOption(kUserNameOption, options);
}
builder.UserID = user_id;
builder.Password = GetOption(kPasswordOption, options);
string catalog;
if (options.TryGetValue(kInitialCatalogOption, out catalog)) {
builder.InitialCatalog = catalog;
}
return new SqlConnectionProvider(builder.ConnectionString);
}
示例4: RegisterKeyboards
private void RegisterKeyboards(IDictionary<string, uint> keyboards)
{
if (keyboards.Count <= 0)
return;
var configRegistry = XklConfigRegistry.Create(XklEngine);
var layouts = configRegistry.Layouts;
Dictionary<string, XkbKeyboardDescription> curKeyboards = KeyboardController.Instance.Keyboards.OfType<XkbKeyboardDescription>().ToDictionary(kd => kd.Id);
foreach (var kvp in layouts)
{
foreach (var layout in kvp.Value)
{
uint index;
// Custom keyboards may omit defining a country code. Try to survive such cases.
string codeToMatch;
if (layout.CountryCode == null)
codeToMatch = layout.LanguageCode.ToLowerInvariant();
else
codeToMatch = layout.CountryCode.ToLowerInvariant();
if ((keyboards.TryGetValue(layout.LayoutId, out index) && (layout.LayoutId == codeToMatch)) ||
keyboards.TryGetValue(string.Format("{0}+{1}", codeToMatch, layout.LayoutId), out index))
{
AddKeyboardForLayout(curKeyboards, layout, index, SwitchingAdaptor);
}
}
}
foreach (XkbKeyboardDescription existingKeyboard in curKeyboards.Values)
existingKeyboard.SetIsAvailable(false);
}
示例5: GetTraceLevel
private static TraceLevel GetTraceLevel(IDictionary<string, string> attributes)
{
string type;
attributes.TryGetValue("type", out type);
if (type == "error")
{
return TraceLevel.Error;
}
string value;
if (attributes.TryGetValue("traceLevel", out value))
{
var traceLevel = Int32.Parse(value);
if (traceLevel <= (int)TraceLevel.Error)
{
return TraceLevel.Error;
}
else if (traceLevel <= (int)TraceLevel.Info)
{
return TraceLevel.Info;
}
}
return TraceLevel.Verbose;
}
示例6: RegisterKeyboards
private void RegisterKeyboards(IDictionary<string, uint> keyboards)
{
if (keyboards.Count <= 0)
return;
var configRegistry = XklConfigRegistry.Create(_engine);
var layouts = configRegistry.Layouts;
foreach (var kvp in layouts)
{
foreach (var layout in kvp.Value)
{
uint index;
// Custom keyboards may omit defining a country code. Try to survive such cases.
string codeToMatch;
if (layout.CountryCode == null)
codeToMatch = layout.LanguageCode.ToLowerInvariant();
else
codeToMatch = layout.CountryCode.ToLowerInvariant();
if ((keyboards.TryGetValue(layout.LayoutId, out index) && (layout.LayoutId == codeToMatch)) ||
keyboards.TryGetValue(string.Format("{0}+{1}", codeToMatch, layout.LayoutId), out index))
{
AddKeyboardForLayout(layout, index, _adaptor);
}
}
}
}
示例7: AddFeatures
private void AddFeatures(Node parent, IEnumerable<IFsFeatDefn> features, IDictionary<IFsFeatDefn, object> values)
{
foreach (IFsFeatDefn feature in features)
{
var complexFeat = feature as IFsComplexFeature;
if (complexFeat != null)
{
var node = new ComplexFeatureNode(complexFeat) {Image = m_complexImage};
object value;
if (values == null || !values.TryGetValue(complexFeat, out value))
value = null;
AddFeatures(node, complexFeat.TypeRA.FeaturesRS, (IDictionary<IFsFeatDefn, object>) value);
parent.Nodes.Add(node);
}
else
{
var closedFeat = feature as IFsClosedFeature;
if (closedFeat != null)
{
var node = new ClosedFeatureNode(closedFeat) {Image = m_closedImage};
object value;
if (values != null && values.TryGetValue(closedFeat, out value))
{
var closedVal = (ClosedFeatureValue) value;
node.IsChecked = closedVal.Negate;
node.Value = new SymbolicValue(closedVal.Symbol);
}
parent.Nodes.Add(node);
}
}
}
}
示例8: typeof
void ITableEntity.ReadEntity(IDictionary<string, EntityProperty> properties, Microsoft.WindowsAzure.Storage.OperationContext operationContext)
{
// This can occasionally fail because someone didn't finish creating the entity yet.
EntityProperty value;
if (properties.TryGetValue("SerializedError", out value))
{
Error = ErrorXml.DecodeString(value.StringValue);
}
else
{
Error = new Error
{
ApplicationName = "TableErrorLog",
StatusCode = 999,
HostName = Environment.MachineName,
Time = DateTime.UtcNow,
Type = typeof(Exception).FullName,
Detail = "Error Log Entry is Corrupted/Missing in Table Store"
};
return;
}
if (properties.TryGetValue("Detail", out value))
{
Error.Detail = value.StringValue;
}
if (properties.TryGetValue("WebHostHtmlMessage", out value))
{
Error.WebHostHtmlMessage = value.StringValue;
}
}
示例9: FindMap
private IObjectMap FindMap(IDictionary<Object, IObjectMap> dic, Object id, Boolean extend = false)
{
if (dic == null || dic.Count <= 0) return null;
IObjectMap map = null;
// 名称不能是null,否则字典里面会报错
if (id == null) id = String.Empty;
// 如果找到,直接返回
if (dic.TryGetValue(id, out map) || dic.TryGetValue(id + "", out map)) return map;
if (id == null || "" + id == String.Empty)
{
// 如果名称不为空,则试一试找空的
if (dic.TryGetValue(String.Empty, out map)) return map;
}
else if (extend)
{
// 如果名称为空,找第一个
foreach (var item in dic.Values)
{
return item;
}
}
return null;
}
示例10: CreateRuntimeSetup
/// <summary>
/// Creates a ScriptRuntimeSetup object which includes the Python script engine with the specified options.
///
/// The ScriptRuntimeSetup object can then be additional configured and used to create a ScriptRuntime.
/// </summary>
/*!*/
public static ScriptRuntimeSetup CreateRuntimeSetup(IDictionary<string, object> options)
{
ScriptRuntimeSetup setup = new ScriptRuntimeSetup();
setup.LanguageSetups.Add(CreateLanguageSetup(options));
if (options != null)
{
object value;
if (options.TryGetValue("Debug", out value) &&
value is bool &&
(bool)value)
{
setup.DebugMode = true;
}
if (options.TryGetValue("PrivateBinding", out value) &&
value is bool &&
(bool)value)
{
setup.PrivateBinding = true;
}
}
return setup;
}
示例11: RuntimeModelElementConstructorMetadata
/// <summary>
/// Initializes a new instance of the <see cref="RuntimeModelElementConstructorMetadata"/> class.
/// </summary>
/// <param name="metadata">The metadata.</param>
public RuntimeModelElementConstructorMetadata(IDictionary<string, object> metadata)
: base(metadata)
{
this.ModelType = (Type)metadata.TryGetValue(nameof(this.ModelType));
this.ModelContractType = (Type)metadata.TryGetValue(nameof(this.ModelContractType));
this.RuntimeType = (Type)metadata.TryGetValue(nameof(this.RuntimeType));
}
示例12: ChannelMetadata
public ChannelMetadata(IDictionary<string, object> metadata)
{
object raw;
if (metadata.TryGetValue("Channel", out raw))
Channel = (int)raw;
if (metadata.TryGetValue("Map", out raw))
Map = (string)raw;
}
示例13: Server
/// <summary>
/// Sets up the webserver and starts it
/// </summary>
/// <param name="options">A set of options</param>
public Server(IDictionary<string, string> options)
{
int port;
string portstring;
IEnumerable<int> ports = null;
options.TryGetValue(OPTION_PORT, out portstring);
if (!string.IsNullOrEmpty(portstring))
ports =
from n in portstring.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
where int.TryParse(n, out port)
select int.Parse(n);
if (ports == null || !ports.Any())
ports = new int[] { DEFAULT_OPTION_PORT };
string interfacestring;
System.Net.IPAddress listenInterface;
options.TryGetValue(OPTION_INTERFACE, out interfacestring);
if (string.IsNullOrWhiteSpace(interfacestring))
interfacestring = Program.DataConnection.ApplicationSettings.ServerListenInterface;
if (string.IsNullOrWhiteSpace(interfacestring))
interfacestring = DEFAULT_OPTION_INTERFACE;
if (interfacestring.Trim() == "*" || interfacestring.Trim().Equals("any", StringComparison.InvariantCultureIgnoreCase))
listenInterface = System.Net.IPAddress.Any;
else if (interfacestring.Trim() == "loopback")
listenInterface = System.Net.IPAddress.Loopback;
else
listenInterface = System.Net.IPAddress.Parse(interfacestring);
// If we are in hosted mode with no specified port,
// then try different ports
foreach(var p in ports)
try
{
// Due to the way the server is initialized,
// we cannot try to start it again on another port,
// so we create a new server for each attempt
var server = CreateServer(options);
server.Start(listenInterface, p);
m_server = server;
m_server.ServerName = "Duplicati v" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
this.Port = p;
if (interfacestring != Program.DataConnection.ApplicationSettings.ServerListenInterface)
Program.DataConnection.ApplicationSettings.ServerListenInterface = interfacestring;
return;
}
catch (System.Net.Sockets.SocketException)
{
}
throw new Exception("Unable to open a socket for listening, tried ports: " + string.Join(",", from n in ports select n.ToString()));
}
示例14: GetNewRequestMessage
/// <summary>
/// Analyzes an incoming request message payload to discover what kind of
/// message is embedded in it and returns the type, or null if no match is found.
/// </summary>
/// <param name="recipient">The intended or actual recipient of the request message.</param>
/// <param name="fields">The name/value pairs that make up the message payload.</param>
/// <returns>
/// A newly instantiated <see cref="IProtocolMessage"/>-derived object that this message can
/// deserialize to. Null if the request isn't recognized as a valid protocol message.
/// </returns>
public IDirectedProtocolMessage GetNewRequestMessage(MessageReceivingEndpoint recipient, IDictionary<string, string> fields)
{
ErrorUtilities.VerifyArgumentNotNull(recipient, "recipient");
ErrorUtilities.VerifyArgumentNotNull(fields, "fields");
RequestBase message = null;
// Discern the OpenID version of the message.
Protocol protocol = Protocol.V11;
string ns;
if (fields.TryGetValue(Protocol.V20.openid.ns, out ns)) {
ErrorUtilities.VerifyProtocol(string.Equals(ns, Protocol.OpenId2Namespace, StringComparison.Ordinal), MessagingStrings.UnexpectedMessagePartValue, Protocol.V20.openid.ns, ns);
protocol = Protocol.V20;
}
string mode;
if (fields.TryGetValue(protocol.openid.mode, out mode)) {
if (string.Equals(mode, protocol.Args.Mode.associate)) {
if (fields.ContainsKey(protocol.openid.dh_consumer_public)) {
message = new AssociateDiffieHellmanRequest(protocol.Version, recipient.Location);
} else {
message = new AssociateUnencryptedRequest(protocol.Version, recipient.Location);
}
} else if (string.Equals(mode, protocol.Args.Mode.checkid_setup) ||
string.Equals(mode, protocol.Args.Mode.checkid_immediate)) {
AuthenticationRequestMode authMode = string.Equals(mode, protocol.Args.Mode.checkid_immediate) ? AuthenticationRequestMode.Immediate : AuthenticationRequestMode.Setup;
if (fields.ContainsKey(protocol.openid.identity)) {
message = new CheckIdRequest(protocol.Version, recipient.Location, authMode);
} else {
ErrorUtilities.VerifyProtocol(!fields.ContainsKey(protocol.openid.claimed_id), OpenIdStrings.IdentityAndClaimedIdentifierMustBeBothPresentOrAbsent);
message = new SignedResponseRequest(protocol.Version, recipient.Location, authMode);
}
} else if (string.Equals(mode, protocol.Args.Mode.cancel) ||
(string.Equals(mode, protocol.Args.Mode.setup_needed) && (protocol.Version.Major >= 2 || fields.ContainsKey(protocol.openid.user_setup_url)))) {
message = new NegativeAssertionResponse(protocol.Version, recipient.Location, mode);
} else if (string.Equals(mode, protocol.Args.Mode.id_res)) {
if (fields.ContainsKey(protocol.openid.identity)) {
message = new PositiveAssertionResponse(protocol.Version, recipient.Location);
} else {
ErrorUtilities.VerifyProtocol(!fields.ContainsKey(protocol.openid.claimed_id), OpenIdStrings.IdentityAndClaimedIdentifierMustBeBothPresentOrAbsent);
message = new IndirectSignedResponse(protocol.Version, recipient.Location);
}
} else if (string.Equals(mode, protocol.Args.Mode.check_authentication)) {
message = new CheckAuthenticationRequest(protocol.Version, recipient.Location);
} else if (string.Equals(mode, protocol.Args.Mode.error)) {
message = new IndirectErrorResponse(protocol.Version, recipient.Location);
} else {
ErrorUtilities.ThrowProtocol(MessagingStrings.UnexpectedMessagePartValue, protocol.openid.mode, mode);
}
}
if (message != null) {
message.SetAsIncoming();
}
return message;
}
示例15: Initialize
public override void Initialize(RazorHost razorHost, IDictionary<string, string> directives)
{
if (ReadSwitchValue(directives, GeneratePrettyNamesTransformer.DirectiveName) == true)
{
var trimLeadingUnderscores = ReadSwitchValue(directives, TrimLeadingUnderscoresKey) ?? false;
_transformers.Add(new GeneratePrettyNamesTransformer(trimLeadingUnderscores));
}
string typeVisibility;
if (directives.TryGetValue(TypeVisibilityKey, out typeVisibility))
{
_transformers.Add(new SetTypeVisibility(typeVisibility));
}
string typeNamespace;
if (directives.TryGetValue(NamespaceKey, out typeNamespace))
{
_transformers.Add(new SetTypeNamespace(typeNamespace));
}
if (ReadSwitchValue(directives, DisableLinePragmasKey) == true)
{
razorHost.EnableLinePragmas = false;
}
else if (ReadSwitchValue(directives, GenerateAbsolutePathLinePragmas) != true)
{
// Rewrite line pragamas to generate bin relative paths instead of absolute paths.
_transformers.Add(new RewriteLinePragmas());
}
if (ReadSwitchValue(directives, ExcludeFromCodeCoverage) == true)
{
_transformers.Add(new ExcludeFromCodeCoverageTransformer());
}
string suffix;
if (directives.TryGetValue(SuffixFileName, out suffix))
{
_transformers.Add(new SuffixFileNameTransformer(suffix));
}
string genericParameters;
if (directives.TryGetValue(GenericParametersKey, out genericParameters))
{
var parameters = from p in genericParameters.Split(',') select p.Trim();
_transformers.Add(new GenericParametersTransformer(parameters));
}
string imports;
if (directives.TryGetValue(ImportsKey, out imports))
{
var values = from p in imports.Split(',') select p.Trim();
_transformers.Add(new SetImports(values, false));
}
base.Initialize(razorHost, directives);
}